JavaScript - document.getElementsByTagName() Method

The getElementsByTagName() method in JavaScript returns all elements with the specified tag name. This method is often used when you want to retrieve all elements of a certain type in the document, such as `<div>`, `<p>`, `<input>`, and more.

Syntax


document.getElementsByTagName("tagname");

In the syntax above, the tagname is the name of the element type (e.g., "div", "p", "input").

Example of document.getElementsByTagName() Method

In this example, we count the total number of `<p>` tags in the document using the getElementsByTagName() method:

Example


<script type="text/javascript">
function countParagraphs() {
    var allParagraphs = document.getElementsByTagName("p");
    alert("Total Paragraphs: " + allParagraphs.length);
}
</script>
        
<h1>Welcome to my webpage</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
<input type="button" onclick="countParagraphs()" value="Count Paragraphs">

Output

When the "Count Paragraphs" button is clicked, an alert will display the total number of `<p>` tags (3 in this example).

Welcome to my webpage

This is the first paragraph.

This is the second paragraph.

This is the third paragraph.

Advanced Example: Using getElementsByTagName() to Access Multiple Elements

In this advanced example, we use the getElementsByTagName() method to change the background color of all elements in the document:

Example


<script type="text/javascript">
function changeDivColors() {
    var allDivs = document.getElementsByTagName("div");
    for (var i = 0; i < allDivs.length; i++) {
    allDivs[i].style.backgroundColor = "lightblue";
    }
    }
</script>
        
<div>First div content</div>
<div>Second div content</div>
<div>Third div content</div>
<input type="button" onclick="changeDivColors()" value="Change Div Colors">

Output

When the "Change Div Colors" button is clicked, the background color of all `
` elements will change to light blue.
First div content
Second div content
Third div content