The examples below use the XML file books.xml.
A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.
Add a node after the last child node
This example uses appendChild() to add a child node to an existing node.
Add a node before a specified child node
This example uses insertBefore() 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.
The appendChild() method adds a child node to an existing node.
The new node is added (appended) after any existing child nodes.
Note: Use insertBefore() if the position of the node is important.
The following code fragment creates an element (<edition>), and adds it after the last child of the first <book> element:
Example explained:
Loop through and append an element to all <book> elements:Try it yourself
The insertBefore() method is used to insert a node before a specified child node.
This method is useful when the position of the added node is important:
Example explained:
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) will both append a new child node to x.
There is no method called addAtribute().
The setAttribute() method creates a new attribute if the attribute does not exist:
Example explained:
Note: If the attribute already exists, the setAttribute() method will overwrite the existing value.
The insertData() method inserts data into an existing text node.
The insertData() method has two parameters:
The following code fragment will add "Easy" to the text node of the first <title> element of the loaded XML:
| WEB HOSTING |
|---|
| Best Web Hosting |
| PHP MySQL Hosting |
| Best Hosting Coupons |
| UK Reseller Hosting |
| Cloud Hosting |
| Top Web Hosting |
| $7.95/mo SEO Hosting |
| Premium Website Design |
| WEB BUILDING |
|---|
| XML Editor - Free Trial! |
| FREE Website BUILDER |
| Free Website Templates Free CSS Templates |
| Make Your Own Website |
| W3SCHOOLS EXAMS |
|---|
|
Get Certified in: HTML, CSS, JavaScript, XML, PHP, and ASP |
| W3SCHOOLS BOOKS |
|---|
|
New Books: HTML, CSS JavaScript, and Ajax |
| STATISTICS |
|---|
|
Browser Statistics Browser OS Browser Display |
| SHARE THIS PAGE |
|---|