Let's see how to add a new element node with appendChild() and insertBefore(), an attribute node with setAttribute() and data into an existing text node with insertData().
Add a Node with appendChild() Method
The appendChild() method adds a node to the end of the list of children of a specified parent node (append).
The syntax is:
element.appendChild(childNode);where childNode is the node to append to the given parent node.
It returns a node that is the appended child (childNode).
Example: add <edition> after the last child of the first <book> element:
newElement = xmlDoc.createElement("edition");
xmlDoc.getElementsByTagName("book")[0].appendChild(newElement);Insert a Node with insertBefore() Method
The insertBefore() method inserts a node before a reference node as a child of a specified parent node.
Example: insert <book> element before the fourth <book> element:
newNode = xmlDoc.createElement("book");
x = xmlDoc.documentElement;
y = xmlDoc.getElementsByTagName("book")[3];
x.insertBefore(newNode,y);Add a New Attribute with setAttribute() Method
The setAttribute() method sets the value of an attribute on the specified element.
Example: add new edition attribute with value First Edition to the first <book> element:
xmlDoc.getElementsByTagName('book')[0].setAttribute("edition","First Edition");Add Text to a Text Node with insertData() Method
The insertData() method inserts data into an existing text node.
The syntax is:
textNode.insertData(offset, data);where:
- offset: number of characters to insert the provided data at.
0is the first character of the string. - string: the string to insert
Example: insert "New String" to the text node of the first <title> element of the loaded XML:
xmlDoc.getElementsByTagName("title")[0].childNodes[0].insertData(0,"New String");