JavaScript-document.getElementsByTagName() Method
The `document.getElementsByTagName()` method retrieves all elements with
the specified tag name.
Syntax:
Below is the syntax of the `getElementsByTagName()` method:
document.getElementsByTagName(tagName)
Example 1:
In this example, we will count the total number of paragraphs in the
document. To achieve this, we use the `document.getElementsByTagName("p")`
method, which returns all the paragraphs.
<html>
<body>
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<p>This is paragraph 3</p>
<script>
var paragraphs =
document.getElementsByTagName('p');
for (var i = 0; i < paragraphs.length; i++) {
console.log(paragraphs[i].innerHTML);
}
</script>
</body>
</html>
Output:
This is paragraph 1
This is paragraph 2
This is paragraph 3
In this paragraph, we will count the total number of paragraphs using the
`getElementsByTagName()` method.
Example 2:
In this example, we will count the total number of h2 and h3 tags used in
the document.
<!DOCTYPE html>
<html>
<head>
<title>Count h2 and h3 tags</title>
</head>
<body>
<h1>Main Heading</h1>
<h2>Subheading 1</h2>
<h2>Subheading 2</h2>
<h2>Subheading 3</h2>
<h3>Sub-subheading 1</h3>
<h3>Sub-subheading 2</h3>
<h3>Sub-subheading 3</h3>
<h3>Sub-subheading 4</h3>
<button
onclick="countTags()">Count h2 and h3 tags</button>
<p id="result"></p>
<script>
function countTags() {
var h2Tags =
document.getElementsByTagName('h2').length;
var h3Tags =
document.getElementsByTagName('h3').length;
var totalTags = h2Tags + h3Tags;
document.getElementById('result').innerHTML =
"Total number of h2 tags: " + h2Tags +
"<br>" +
"Total number of h3 tags: " + h3Tags +
"<br>" +
"Total number of h2 and h3 tags: " + totalTags;
}
</script>
</body>
</html>
Output:
Main Heading
Subheading 1
Subheading 2
Subheading 3
Sub-subheading 1
Sub-subheading 2
Sub-subheading 3
Sub-subheading 4
Count h2 and h3 tags
Total number of h2 tags: 3
Total number of h3 tags: 4
Total number of h2 and h3 tags: 7
More topic in JavaScript