Sunday, February 8, 2026
HomeLanguagesPHP | DOMElement setAttributeNode() Function

PHP | DOMElement setAttributeNode() Function

The DOMElement::setAttributeNode() function is an inbuilt function in PHP which is used to add a new attribute node to element.

Syntax:

DOMAttr DOMElement::setAttributeNode( DOMAttr $attr )

Parameters: This function accepts a single parameter $attr which holds the attribute node to be added.

Return Value: This function returns an DOMAttr value containing old node if the value has been replaced or NULL.

Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly.

Below given programs illustrate the DOMElement::setAttributeNode() function in PHP:

Program 1:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
   
// Create an element
$node = $dom->createElement("p", 'neveropen');
   
// Add the node to the dom
$newnode = $dom->appendChild($node);
   
// Create a DOMAttr instance which
// increase the font-size
$attr = new DOMAttr('style', 'font-size: 80px;');
  
// Set the attribute
$newnode->setAttributeNode($attr);
   
// View the XML
echo $dom->saveXML();
?>


Output:

<?xml version="1.0"?>
<p style="font-size: 80px;">neveropen</p>

Program 2:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<root>
    <html>
        <h1 id=\"my_id\"> Geeksforneveropen </h1>
        <h2> Second heading </h2>
    </html>
</root>");
  
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
   
echo "Before the addition of attributes: <br>";
  
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
   
// Create a DOMAttr instance
$attr = new DOMAttr('class', 'value');
  
// Add the new attribute
$node->setAttributeNode($attr);
   
echo "<br>After the addition of attributes: <br>";
   
// Get the attribute count
$attributeCount = $node->attributes->count();
echo 'No of attributes => ' . $attributeCount;
?>


Output:

Before the addition of attributes:
No of attributes => 1
After the addition of attributes:
No of attributes => 2

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32493 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6864 POSTS0 COMMENTS
Nicole Veronica
11990 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12084 POSTS0 COMMENTS
Shaida Kate Naidoo
7000 POSTS0 COMMENTS
Ted Musemwa
7241 POSTS0 COMMENTS
Thapelo Manthata
6951 POSTS0 COMMENTS
Umr Jansen
6936 POSTS0 COMMENTS