Easy Tutorial
❮ Dom Prop Attr Isid Dom Met Node Replacechild ❯

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

Add a new attribute

Add data to a text 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:

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:

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:

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:

The following code snippet will add "Easy" to the text node of the first <title> element of the loaded XML:

Example

❮ Dom Prop Attr Isid Dom Met Node Replacechild ❯