Saturday, September 21, 2019

Javascript - document.getElementsByTagName() method

The document.getElementsByTagName() method returns all the element of specified tag name.

The syntax of the getElementsByTagName() method is given below:

  1. document.getElementsByTagName("name")  
Here, name is required.

Example of document.getElementsByTagName() method

In this example, we going to count total number of paragraphs used in the document. To do this, we have called the document.getElementsByTagName("p") method that returns the total paragraphs.
  1. <script type="text/javascript">  
  2. function countpara(){  
  3. var totalpara=document.getElementsByTagName("p");  
  4. alert("total p tags are: "+totalpara.length);  
  5.   
  6. }  
  7. </script>  
  8. <p>This is a pragraph</p>  
  9. <p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>  
  10. <p>Let's see the simple example</p>  
  11. <button onclick="countpara()">count paragraph</button>  

Output of the above example

This is a pragraph
Here we are going to count total number of paragraphs by getElementByTagName() method.
Let's see the simple example

Another example of document.getElementsByTagName() method

In this example, we going to count total number of h2 and h3 tags used in the document.
  1. <script type="text/javascript">  
  2. function counth2(){  
  3. var totalh2=document.getElementsByTagName("h2");  
  4. alert("total h2 tags are: "+totalh2.length);  
  5. }  
  6. function counth3(){  
  7. var totalh3=document.getElementsByTagName("h3");  
  8. alert("total h3 tags are: "+totalh3.length);  
  9. }  
  10. </script>  
  11. <h2>This is h2 tag</h2>  
  12. <h2>This is h2 tag</h2>  
  13. <h3>This is h3 tag</h3>  
  14. <h3>This is h3 tag</h3>  
  15. <h3>This is h3 tag</h3>  
  16. <button onclick="counth2()">count h2</button>  
  17. <button onclick="counth3()">count h3</button>  

Output of the above example

This is h2 tag

This is h2 tag

This is h3 tag

This is h3 tag

This is h3 tag

 

Note: Output of the given examples may differ on this page because it will count the total number of para , total number of h2 and total number of h3 tags used in this document.

No comments:

Post a Comment