XML DOM Adding Nodes
Try it - Example
The following example uses the XML file books.xml.
function loadXMLDoc(), located in an external JavaScript, used to load the XML file.
Add a node after the last child node
This example uses the appendChild() method to add a child node to an existing node.
Add a node before the specified child node
This example uses the insertBefore() method to insert a node before a specified child node.
Add a new attribute
This example uses the setAttribute() method to add a new attribute.
Add data to a text node
This example uses insertData() to insert data into an existing text node.
Adding a Node - 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 matters, use the insertBefore() method.
The following code snippet creates an element (
Example
xmlDoc=loadXMLDoc("books.xml");
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Create a new node
- Append this node to the first
Element
Loop through and append to all
Inserting a Node - insertBefore()
The insertBefore() method is used to insert a node before the specified child node.
This method is useful when the position of the node being added matters:
Example
xmlDoc=loadXMLDoc("books.xml");
newNode=xmlDoc.createElement("book");
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[3];
x.insertBefore(newNode,y);
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Create a new element node
- Insert this new node before the last
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) can both append a new child node to x.
Add a New Attribute
The addAtribute() method does not exist.
If the attribute does not exist, setAttribute() can create a new attribute:
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Replace the first
set (create) the value of the element's "edition" attribute to "first"
**Note:** If the attribute already exists, the setAttribute() method 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 first element of the loaded XML
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.insertData(0,"Easy ");
Try it »