XML DOM getElementsByTagName() Method
Definition and Usage
The getElementsByTagName() method returns a NodeList of all elements with the specified name.
Syntax:
getElementsByTagName(name)
Parameter | Description |
---|---|
name | String value, specifying the tag name to be searched. The value "*" matches all nodes. |
Description
This method traverses the descendants of the specified element, returning an array of Element nodes (which is actually a NodeList object), representing all document elements with the specified tag name. The order of elements in the returned array is the same as their appearance in the document source code.
Note that the Document interface also defines the getElementsByTagName() method, which is similar to this method but traverses the entire document instead of traversing the descendants of a specific element.
Example
In all examples, we will use XML files books.xml, and JavaScript functions loadXMLDoc().
The following code snippet displays the values of all <title> elements in "books.xml":
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('title')
;
for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
The output of the above code is:
Everyday Italian Harry Potter XQuery Kick Start Learning XML