Document.getElementsByTagName()

Returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

Syntax

var elements = document.getElementsByTagName(name);

elements is a live HTMLCollection (but see the note below) of found elements in the order they appear in the tree.

name is a string representing the name of the elements. The special string "*" represents all elements.

Example

In the following example, getElementsByTagName() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName() and the functionally identical Element.getElementsByTagName(), which starts the search at a specific element within the DOM tree.

Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested <div> elements).

Notes

When called on an HTML document, getElementsByTagName() lower-cases its argument before proceeding. This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. document.getElementsByTagNameNS() is useful in that case. See also bug 499656.