DOM:element.getElementsByTagName

« DOM Reference

Summary

Returns a list of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. Consequently, there is no need to call several times element.getElementsByTagName with the same element and arguments.

Syntax

elements = element.getElementsByTagName(tagName)

  • elements is a live NodeList (but see the note below) of found elements in the order they appear in the subtree. If no elements were found, the NodeList is empty.
  • element is the element from where the search should start. Note that only the descendants of this element are included in the search, but not the element itself.
  • tagName is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used.

Note: While the W3C DOM 3 Core specification says elements is a NodeList that was simply because of a an attempt to have the "core" specification not depend on the "html" specification at that time. The DOM 4 draft says that elements is an HTMLCollection.

Gecko/Firefox currently returns a NodeList (Bug 162927) but starting with Gecko/Firefox 19, this method will return HTMLCollection (Bug 799464). Internet Explorer returns a HTMLCollection. WebKit returns a NodeList. Opera also returns a NodeList, but with a namedItem method implemented, which makes it similar to a HTMLCollection.

Example

// check the alignment on a number of cells in a table. 
var table = document.getElementById("forecast-table"); 
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
    var status = cells[i].getAttribute("data-status"); 
    if ( status == "open" ) { 
        // grab the data 
    }
}

Notes

When called on an HTML element in an HTML document, getElementsByTagName lowercases its argument before proceeding. This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. element.getElementsByTagNameNS works in that case. See also bug 499656.

element.getElementsByTagName is similar to document.getElementsByTagName, except that its search is restricted to those elements which are descendants of the specified element.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 (Yes) 5.5 (Yes) (Yes)
getElementsByTagName("*") 1.0 (Yes) 6.0 (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)

Specifications

Document Tags and Contributors

 Contributors to this page: Anonymous
 Last updated by: Anonymous,