Skip to main content

XML DOM: Add Nodes

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 appenChild() Method

The appendChild() method adds a node to the end of the list of children of a specified parent node (append).

note

Use insertBefore() if the position of the node is important.

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.

note

This method is useful when the position of the added node is important.

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);
note

If the second parameter of insertBefore() is null, the new node will be added after the last existing child node.

note

x.insertBefore(newNode, null) and x.appendChild(newNode) will both append a new child node to x.

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");
note

The setAttribute() method will create a new attribute if the attribute does not exist. Otherwise, if the attribute already exists, the setAttribute() method will overwrite the existing value.

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. 0 is 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");