XML DOM Advanced XML DOM - Advanced Earlier in this tutorial, we introduced the XML DOM and used the XML DOM's getElementsByTagName() method to retrieve data from an XML document. In this chapter we will combine some other important XML DOM methods. You can learn more about XML DOM in our XML DOM tutorial. Get the value of the element in the XML file used in the following example: books.xml. The following example retrieves the text value of the first <title> element: Example
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
Try it »
The following example retrieves the text value of the "lang" attribute of the first <title> element:
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
Try it »
The following example changes the text value of the first <title> element:
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];x.nodeValue="Easy Cooking";
Try it »
The XML DOM's setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute.
The following example creates a new attribute (edition="first") and adds it to each <book> element:
x=xmlDoc.getElementsByTagName("book");for(i=0;i<x.length;i++){x[i].setAttribute("edition","first");}
Try it »
The XML DOM's createElement() method creates a new element node.
The XML DOM's createTextNode() method creates a new text node.
The XML DOM's appendChild() method adds a child node to a node (after the last child node).
To create a new element with text content, create a new element node and a new text node at the same time, and then append it to the existing node.
The following example creates a new element (<edition>) with the following text: First, and then adds it to the first <book> element:
newel=xmlDoc.createElement("edition");newtext=xmlDoc.createTextNode("First");newel.appendChild(newtext);x=xmlDoc.getElementsByTagName("book");x[0].appendChild(newel);
Try it »
Example explanation
Create an <edition> element
Create a text node with value "First"
Append this text node to the new <edition> element
Append the <edition> element to the first <book> element
The following example deletes the first node of the first <book> element:
x=xmlDoc.getElementsByTagName("book")[0];x.removeChild(x.childNodes[0]);
Try it »
Note: The results of the above example may vary depending on the browser used. Firefox treats newline characters as empty text nodes, but Internet Explorer does not. You can read more about this problem and how to avoid it in our XML DOM tutorial.