JavaScript - getElementsByTagName() method

revision:


Category : document

The getElementsByTagName method of Document interface 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.

The getElementsByTagName() method returns a collection of all elements with a specified tag name. The method returns an HTMLCollection. The getElementsByTagName() property is read-only.

Syntax :

        getElementsByTagName(name)
    

Parameters:

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

Examples:

            <script>
                function getAllParaElems() {
                  const allParas = document.getElementsByTagName("p");
                  const num = allParas.length;
                  alert(`There are ${num} paragraph in this document`);
                }
          
                function div1ParaElems() {
                  const div1 = document.getElementById("div1");
                  const div1Paras = div1.getElementsByTagName("p");
                  const num = div1Paras.length;
                  alert(`There are ${num} paragraph in #div1`);
                }
          
                function div2ParaElems() {
                  const div2 = document.getElementById("div2");
                  const div2Paras = div2.getElementsByTagName("p");
                  const num = div2Paras.length;
                  alert(`There are ${num} paragraph in #div2`);
                }
              </script>
              <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>
            
        

Category : element

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.getElementsByTagName() with the same element and arguments repeatedly if the DOM changes in between calls.

When called on an HTML element in an HTML document, getElementsByTagName lower-cases the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS(), which preserves the capitalization of the tag name.

Element.getElementsByTagName is similar to Document.getElementsByTagName(), except that it only searches for elements that are descendants of the specified element.

Syntax :

        elements.getElementsByTagName(tagName)
    

Parameters:

tagName : required; is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used.

Examples:

          // Check the status of each data cell in a table
          const table = document.getElementById("forecast-table");
          const cells = table.getElementsByTagName("td");
          for (const cell of cells) {
            const status = cell.getAttribute("data-status");
            if (status === "open") {
              // Grab the data
            }
          }
        

Practical examples

example: get all elements with the tag name "li".

An unordered list:

  • Coffee
  • Tea
  • Milk

The innerHTML of the second li element is:

code:
                  <div>
                    <p>An unordered list:</p>
                    <ul>
                      <li>Coffee</li>
                      <li>Tea</li>
                      <li>Milk</li>
                    </ul>
                    <p>The innerHTML of the second li element is:</p>
                    <p id="tag-1"></p>
                  </div>
                  <script>
                    const collection = document.getElementsByTagName("li");
                    document.getElementById("tag-1").innerHTML = collection[1].innerHTML;
                  </script>
              

example: get all elements in the document.

An unordered list:

  • Coffee
  • Tea
  • Milk

The tag name of all elements:

code:
                <div>
                  <p>An unordered list:</p>
                  <ul>
                    <li>Coffee</li>
                    <li>Tea</li>
                    <li>Milk</li>
                  </ul>
                  <p>The tag name of all elements:</p>
                  <p id="tag-2"></p>
                </div>
                <script>
                  const collection1= document.getElementsByTagName("*");
                  let text = ""
                  for (let i = 0; i < collection1.length; i++) {
                    text += collection1[i].tagName + "<br>";
                  }
                  document.getElementById("tag-2").innerHTML = text;
                </script>
              

example: change the properties of multiple elements

DOM getElementsByTagName()

This is the first paragraph.
This is the second paragraph.
This is the third paragraph.
code:
                <div>
                  <h4 style="color: green;">DOM getElementsByTagName()</h4>
                  <a>This is the first paragraph.</a><br>
                  <a>This is the second paragraph.</a><br>
                  <a>This is the third paragraph.</a><br>
                  <button onclick="runFunction()">Try it</button>
              </div>
              <script>
                  function runFunction() {
                      var doc = document.getElementsByTagName("a");
                      var i;
                      for (i = 0; i < doc.length; i++) {
                          doc[i].style.backgroundColor = "green";
                          doc[i].style.color = "white";
                      }
                  }
                  
              </script>