Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

HTML | DOM getElementsByTagName() Method

  • Last Updated : 25 Jul, 2019

The getElementsByTagName() method in HTML returns the collection of all the elements in the document with the given tag name. To extract any info just iterate through all the elements using the length property.

Syntax:

var elements = document.getElementsByTagName(name);

Where:

  • elements is a collection of all the found elements in the order they appear with the given tag name.
  • name is a string representing the name of the elements. The special string “*” represents all elements.

Example 1:




<!DOCTYPE html>
<html>
    <head>
        <title>DOM getElementsByTagName() Method</title>
    </head>
    <body style = "text-align: center">
        <h1 style = "color: green;">
            GeeksforGeeks
        </h1>
          
        <h2 >
            DOM getElementsByTagName() 
        </h2>
          
        <p>A computer science portal for geeks.</p>
  
        <button onclick="geek()">Try it</button>
        <script>
        function geek() {
          var doc = document.getElementsByTagName("p");
          doc[0].style.background = "green";
          doc[0].style.color = "white";
        }
        </script>
  
    </body>
</html>

Output:
Before click on button:
tagname
After click on button:
tagname

Example 2:




<!DOCTYPE html>
<html>
    <head>
        <title>DOM getElementsByTagName() Method</title>
    </head>
    <body style = "text-align: center">
  
        <h2 style = "color: green;">
            DOM getElementsByTagName() 
        </h2>
          
        <p>This is the first paragraph.</p>
          
        <p>This is the second paragraph.</p>
          
        <p>This is the third paragraph.</p>
          
        <button onclick="geek()">Try it</button>
          
        <script>
        function geek() {
          var doc = document.getElementsByTagName("P");
          var i;
          for (i = 0; i < doc.length; i++) {
            doc[i].style.backgroundColor = "green";
            doc[i].style.color = "white";
          }
        }
        </script>
  
    </body>
</html>

Output:
Before click on button:
tagname
After click on button:
tagname

Supported Browsers: The browser supported by getElementsByTagName() method are listed below:

  • Google Chrome 1.0
  • Internet Explorer 6.0
  • Firefox 3.0
  • Opera 9.5
  • Safari 3.0

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!