PHP | DOMElement setIdAttributeNode() Function

The DOMElement::setIdAttributeNode() function is an inbuilt function in PHP which is used to declare the attribute specified by DOMAttr instance to be of type ID.

Syntax:

void DOMElement::setIdAttributeNode( DOMAttr $attr, bool $isId )

Parameters: This function accepts two parameters as mentioned above and described below:



  • $attr: It specifies the attribute as a DOMAttr instance.
  • $isId: It specifies whether if you want name to be of type ID.

Return Value: This function returns nothing.

Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly or DOM_NOT_FOUND, if name is not an attribute of this element.

Below examples illustrate the DOMElement::setIdAttributeNode() function in PHP:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
   
// Enable validate on parse
$dom->validateOnParse = true;
   
// Create a div element
$element = $dom->appendChild(new DOMElement
                  ('div', 'GEEKSFORGEEKS'));
  
// Create the id element 
$id = new DOMAttr('id', 'geeksforgeeks');
  
// Create a id attribute to div
$attr = $element->setAttributeNode($id);
  
// Set that attribute as id
$element->setIDAttributeNode($id, true);
  
echo $dom->saveXML();
?>

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
   
// Enable validate on parse
$dom->validateOnParse = true;
   
// Create a div element
$element = $dom->appendChild(new DOMElement
                 ('div', 'Hey ! This is my content.'));
  
// Create the id element 
$id = new DOMAttr('id', 'geeksforgeeks');
  
// Create a id attribute to div
$attr = $element->setAttributeNode($id);
  
// Set that attribute as id
$element->setIDAttributeNode($id, true);
  
// Get the text of element with id='geeksforgeeks'
// just to see if it works
$value = $dom->getElementById('geeksforgeeks')->textContent;
    
echo $value;
?>

chevron_right


Output:

Hey ! This is my content.

Reference: https://www.php.net/manual/en/domelement.setidattributenode.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.