Skip to main content

XML DOM: Create Nodes

Let's see how to create an element node, an attribute with createAttribute() and setAttribute(), a new text node, a CDATA section node, and a comment node.

Create a New Element Node

The createElement() method creates a new element node.

For example: create a new child element in a <book> element:

newElement = xmlDoc.createElement("releaseDate");  
xmlDoc.getElementsByTagName("book")[0].appendChild(newElement);

Create a New Attribute Node using createAttribute()

The createAttribute() is used to create a new attribute node.

For example: create a new attribute in a <book> element:

// create the new attribute
newAttribute = xmlDoc.createAttribute("releaseYear");
// set the value of the attribute
newAttribute.nodeValue = "2022";
// add the new attribute to <book> element
xmlDoc.getElementsByTagName("book")[0].setAttributeNode(newAttribute);
note

If the attribute already exists, it is replaced by the new one!

Create an Attribute Using setAttribute()

Since the setAttribute() method creates a new attribute if the attribute does not exist, it can be used to create a new attribute.

For example: create subtitle attribute for the <book> element:

xmlDoc.getElementsByTagName("book")[0].setAttribute("subtitle","Fancy Subtitle");

Create a Text Node

The createTextNode() method creates a new text node.

For example: create a text element node to be added to a new element node, which in turn must be added to a book element

newElement = xmlDoc.createElement("edition");  
newText = xmlDoc.createTextNode("first");
newElement .appendChild(newText);

xmlDoc.getElementsByTagName("book")[0].appendChild(newEle);

Create a CDATA Section Node

The createCDATASection() method creates a new CDATA section node.

For example: append CDATA to the first <book> element:

newCDATA = xmlDoc.createCDATASection("Special Offer");  

xmlDoc.getElementsByTagName("book")[0].appendChild(newCDATA);

Create a Comment Node

The createComment() method creates a new comment node.

For example: add a comment node to the first <book> element:

newComment = xmlDoc.createComment("This is a comment");  

xmlDoc.getElementsByTagName("book")[0].appendChild(newComment);