XML DOM Adding Nodes
Try It Yourself - Example
The following example uses the XML file books.xml. loadXMLDoc(), located in an external JavaScript, is used to load the XML file.
Add a node after the last child node
Add a node before a specified child node
Adding Nodes - appendChild()
The appendChild() method adds a child node to an existing node.
The new node is added (appended) after any existing child nodes.
Note: If the position of the node is important, use the insertBefore() method.
The following code snippet creates an element (<edition>), and appends it after the last child node of the first <book> element:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new node <edition>
Append this node to the first <book> element
Iterate and append an element to all <book> elements: Try It Yourself
Inserting Nodes - insertBefore()
The insertBefore() method is used to insert a node before a specified child node.
This method is useful when the position of the node being added is important:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Create a new element node <book>
Insert this new node before the last <book> element node
If the second parameter of insertBefore() is null, the new node will be added after the last existing child node.
x.insertBefore(newNode,null) and x.appendChild(newNode) both append a new child node to x.
Adding New Attributes
The method addAtribute() does not exist.
If the attribute does not exist, setAttribute() can create a new attribute:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Set (create) the value of the "edition" attribute of the first <book> element to "first"
Note: If the attribute already exists, setAttribute() will overwrite the existing value.
Adding Text to a Text Node - insertData()
The insertData() method inserts data into an existing text node.
The insertData() method has two parameters:
offset - where to start inserting characters (starting from 0)
string - the string to insert
The following code snippet will add "Easy" to the text node of the first <title> element of the loaded XML: