JavaScript document.getElementsByTagName()

The JavaScript getElementsByTagName() method returns all elements with specified tag names. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <h2>getElementsByTagName()</h2>
   <p>This is para one</p>
   <p>This is para two</p>

   <h2>The getElementsByTagName() Method</h2>
   <p>This is para three</p>
   <p>This is para four</p>
   
   <script>
      var ec = document.getElementsByTagName("h2");
      for(var i=0; i<ec.length; i++)
      {
         ec[i].style.backgroundColor = "purple";
         ec[i].style.padding = "12px";
         ec[i].style.color = "white";
      }

      var ec = document.getElementsByTagName("p");
      for(var i=0; i<ec.length; i++)
      {
         ec[i].style.color = "red";
      }
   </script>
   
</body>
</html>
Output

getElementsByTagName()

This is para one

This is para two

The getElementsByTagName() Method

This is para three

This is para four

In above example, the following statement:

var ec = document.getElementsByTagName("h2");

returns all H2 elements and initialized to ec variable, as collection. And next using the for loop, I've applied some styles to all H2 elements, one by one. Same process applied to all P (paragraph) elements.

JavaScript getElementsByTagName() Syntax

The syntax of getElementsByTagName() method in JavaScript, is:

document.getElementsByTagName(tag)

Note - The document.getElementsByTagName("*") returns collection of all elements available in current HTML document.

JavaScript getElementsByTagName() Example

To get the collection of all elements with specified tag name, available inside specified element, proceed in this way:

element.getElementsByTagName(tag)

where element refers to the element (parent element), inside which, all elements with specified tag name, will be returned. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>This is para one</p>
   <div id="myDiv">
      <p>This is para two</p>
      <p>This is para three</p>
   </div>
   <p>This is para four</p>
   
   <script>
      var element = document.getElementById("myDiv");
      var ec = element.getElementsByTagName("p");
      for(var i=0; i<ec.length; i++)
         ec[i].style.color = "red";
   </script>
   
</body>
</html>
Output

This is para one

This is para two

This is para three

This is para four

JavaScript Online Test


« Previous Tutorial Next Tutorial »