Home >>Javascript Tutorial >getElementsByTagName() method
The document.getElementsByTagName method in JavaScript generally return the elements of a specified tag name.
Here is the syntax of getElementsByTagName() method in JavaScript:
document.getElementsByTagName("name")
Please note that here name is required.
Below is an extremely simple example of document.getElementsByTagName() method in JavaScript:
Here, the total number of paragraphs used in the document will be counted using the document.getElementsByTagName() method.
<script type="text/javascript"> function countpara(){ var totalpara=document.getElementsByTagName("p"); alert("total p tags are: "+totalpara.length); } </script> <p>This is a pragraph</p> <p>Here the total number of paragraphs will be counted by getElementByTagName() method.</p> <p>Let's see the simple example</p> <button onclick="countpara()">count the paragraph</button>
This is a pragraph
Here the total number of paragraphs will be counted by getElementByTagName() method.
Let's see the simple example
Let's take another example to understand the document.getElementByTagName() method. Here is in this example the total number of h2 and h3 tags used in a document will be counted.
<script type="text/javascript"> function counth2(){ var totalh2=document.getElementsByTagName("h2"); alert("total h2 tags are: "+totalh2.length); } function counth3(){ var totalh3=document.getElementsByTagName("h3"); alert("total h3 tags are: "+totalh3.length); } </script> <h2>This is h2 tag</h2> <h2>This is h2 tag</h2> <h3>This is h3 tag</h3> <h3>This is h3 tag</h3> <h3>This is h3 tag</h3> <button onclick="counth2()">count h2</button> <button onclick="counth3()">count h3</button>
When the buttons are clicked the pop-up will display the total number of values.