With DOM, you can visit every node in the XML document. You can search for and visit nodes in several ways: apply the getElementsByTagName () method to parentNode and firstChil of an element node.
With DOM, you can visit every node in the XML document.
Find and visit nodes
You can use several methods to find the elements you want to control:
By applying the getElementsByTagName () method
Apply the parentNode, firstChild, and lastChild attributes of an element node.
GetElementsByTagName ()
The getElementsByTagName () method can be used to search for any XML element in all documents.
This method ignores the structure of the document. Assume that all Element, the getElementsByTagName () method will find them all, regardless of these The level at which the element is located.
That is to say, this method will give you any XML elements you need, regardless of their position!
The getElementsByTagName () method returns all elements (as a node list) with the specified tag name. these elements are the descendants of the elements when you apply this method.
GetElementsByTagName () can be used for any XML element:
GetElementsByTagName () syntax
GetElementsByTagName ("tagname ");
Example
The following example will return all A node list of elements:
XmlDoc. getElementsByTagName ("book ");
Node list
When a node list is applied, we usually store the list in a variable, like this:
Var x = xmlDoc. getElementsByTagName ("book ");
Now, variable x contains all A list of elements, and we can visit these through their index number. Element.
Note: The index starts at 0.
You can use the length attribute to traverse the node list cyclically:
Reference content is as follows:
Var x = xmlDoc. getElementsByTagName ("book ");
For (var I = 0; I {
// Do something with each Element
}
You can also visit a specific element by applying the index number.
Visit the third Element, you can write as follows:
Var y = x [2];
ParentNode, firstChild, and lastChild
Attributes parentNode, firstChild, and lastChild observe the structure of the document and can be used for short-interval travel in the document.
See the following XML snippet:
Reference content is as follows:
Everyday Italian
Giada De Laurentiis
2005
30.00
In the preceding XML code,Element is The first child element (firstChild) of the element ), Element is The last child element (lastChild) of the element ).
At the same time, Element is ,, And ParentNode)
Root node
There is a special document attribute that can be used to visit these tags:
Document.doc umentElement
This attribute returns the root node that exists in the XML and HTML documents.