XML DOM Creating Nodes
Try it Yourself - Examples
The following examples use the XML file books.xml. loadXMLDoc(), located in an external JavaScript, is used to load the XML file.
Creating an Attribute Node with createAttribute
Creating an Attribute Node with setAttribute
Creating a New Element Node
The createElement() method creates a new element node:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new element node <edition>
Append this element node to the first <book> element
Loop through and add an element to all <book> elements: Try it Yourself
Creating a New Attribute Node
The createAttribute() method is used to create a new attribute node:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new attribute node "edition"
Set the value of the attribute node to "first"
Add this new attribute node to the first <title> element
Loop through all <title> elements and add a new attribute node: Try it Yourself
Note: If the attribute already exists, it is replaced by the new attribute.
Creating an Attribute with setAttribute()
Since the setAttribute() method can create a new attribute if it does not exist, we can use this method to create a new attribute.
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Set (create) an "edition" attribute with the value "first" for the first <book> element
Loop through all <title> elements and add a new attribute: Try it Yourself
Creating a Text Node
The createTextNode() method creates a new text node:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new element node <edition>
Create a new text node with the text "first"
Append the new text node to the element node
Append the new element node to the first <book> element
Add an element node with a text node to all <book> elements: Try it Yourself
Creating a CDATA Section Node
The createCDATASection() method creates a new CDATA section node.
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new CDATA section node
Append this new CDATA section node to the first <book> element
Loop through and add a CDATA section to all <book> elements: Try it Yourself
Creating a Comment Node
The createComment() method creates a new comment node.
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new comment node
Append this new comment node to the first <book> element
Loop through and add a comment node to all <book> elements: Try it Yourself