Visit Mozilla.org

DOM:document.getElementsByTagName

From MDC

« Gecko DOM Reference

Contents

[edit] Summary

Returns a list of elements with the given tag name. The complete document is searched, including the root node.

[edit] Syntax

elements = document.getElementsByTagName(name)
  • elements is a live NodeList 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.

[edit] Example

In the following example getElementsByTagName starts from a particular parent element, and searches topdown recursively through the DOM from that parent element, looking for child elements matching the tag name parameter.

Note that when the node on which getElementsByTagName is invoked is not the document node, in fact the element.getElementsByTagName method is used.

<html>

<head>
<title>getElementsByTagName example</title>

<script type="text/javascript">

function getAllParaElems()
{
  var allParas = document.getElementsByTagName("p");

  var num = allParas.length;

  alert("There are " + num + " <p> elements in this document");
}


function div1ParaElems()
{
  var div1 = document.getElementById("div1")
  var div1Paras = div1.getElementsByTagName("p");

  var num = div1Paras.length;

  alert("There are " + num + " <p> elements in div1 element");
}


function div2ParaElems()
{
  var div2 = document.getElementById("div2")
  var div2Paras = div2.getElementsByTagName("p");

  var num = div2Paras.length;

  alert("There are " + num + " <p> elements in div2 element");
}

</script>
</head>

<body style="border: solid green 3px">
<p>Some outer text</p>
<p>Some outer text</p>

  <div id="div1" style="border: solid blue 3px">
    <p>Some div1 text</p>
    <p>Some div1 text</p>
    <p>Some div1 text</p>

    <div id="div2" style="border: solid red 3px">
    <p>Some div2 text</p>
    <p>Some div2 text</p>
    </div>
  </div>

<p>Some outer text</p>
<p>Some outer text</p>

<button onclick="getAllParaElems();">
 show all p elements in document</button><br />

<button onclick="div1ParaElems();">
 show all p elements in div1 element</button><br />

<button onclick="div2ParaElems();">
 show all p elements in div2 element</button>

</body>
</html>

[edit] Specification

DOM Level 2 Core: Document.getElementsByTagName