XML DOM getElementsByTagName() Method

Document Object Reference Manual

Definition and Usage

The getElementsByTagName() method can return a node list of all elements with the specified name.

Syntax:

getElementsByTagName(name)
Parameter Description
name A string value that specifies the tag name to be searched. The value "*" matches all tags.

Return value

Read-only array of Element nodes with the specified tag in the document tree (technically, it is NodeList object). The order of the returned element nodes is the same as their appearance in the source document.

Description

This method will return a NodeList object(which can be treated as a read-only array), this object stores all Element nodes with the specified tag name in the document, and their order is the same as their appearance in the source document.NodeList objectis 'live', which means that if elements with the specified tag name are added or deleted in the document, its content will automatically update as necessary.

Note that the Element interface defines a method with the same name, which only searches the subtree of the document. In addition, the HTMLDocument interface defines getElementsByName() methodSearch elements based on the value of the name attribute (not the tag name).

Example

The following code can be used to search and traverse all <h1> tags in the HTML document:

var headings = document.getElementsByTagName("h1");
for (var i = 0; i < headings.length; i++)  {
  var h = headings[i];
}

Example

In all examples, we will use the XML file books.xml, and JavaScript functions loadXMLDoc().

The following code snippet can display the values of all <title> elements in "books.xml":

xmlDoc=loadXMLDoc("/example/xdom/books.xml");
var x=xmlDoc.getElementsByTagName('title');
for (i=0;i<x.length;i++)
  {
  document.write(x[i].childNodes[0].nodeValue)
  document.write("<br />")
  }

Output:

Harry Potter
Everyday Italian
XQuery Kick Start
Learning XML

Document Object Reference Manual