JavaScript – document getElementsByTagName

What is document.getElementsByTagName() method in Javascript ?

Document getElementsByTagName() method returns the collection of all the elements for the provided tag name.

Syntax :


document :

This refers the current document (ie) HTML page.

name :

This refers to the “name” of the elements

The special string “*” represents all elements.

return value :

This function returns the collection of matched/found elements listed in order for the provided tag name.

If the “name” element doesn’t exist, It returns “null”

We can also find the length of the elements by


Complete javascript tutorial !!!

Click to Learn More about – Javascript online learning

1. document.getElementsByTagName(“name”).length;

In this example we have 5 paragraph tags, 3 H1 tags and 2 H2 tags.

We want to find the count of each tag by clicking the buttons.And printing the count of each tags next to the buttons.

Example :

<!DOCTYPE html>

		<title>Our title</title>
			width: 30%;
			height: 30%;
			padding: 20px;
			margin: 10px;
			border: 2px solid green;
			font-size: 20px;
			width: 30%;
			height: 30%;
			margin: 10px;
			border: 2px solid green;
			padding: 20px;
			font-size: 20px;
		.b1, .b2, .b3, .b4, .b5, .s1, .s2, .s3, .s4, .s5{
			font-size: 20px;
			function getCountP1() { 
			var pid1 = document.getElementsByTagName("p"); 
		var sid1 = document.getElementById("sid1"); 
                        sid1.innerHTML = sid1.innerHTML + "" +  pid1.length;
			function getCountH1() { 
                        var hid1 = document.getElementsByTagName("h1"); 
                        var sid2 = document.getElementById("sid2"); 
                        sid2.innerHTML = sid2.innerHTML + "" +  hid1.length;
			function getCountH2() { 
                        var hid2 = document.getElementsByTagName("h2"); 
                        var sid3 = document.getElementById("sid3"); 
                        sid3.innerHTML = sid3.innerHTML + "" +  hid2.length;

		<div id="dId-1">
			<p>This is Paragraph1 P1</p>
			<p>This is Paragraph2 P2</p>
			<p>This is Paragraph3 P3</p>
			<p>This is Paragraph4 P4</p>
			<p>This is Paragraph5 P5</p>
			<h1>This is Heading1 H1</h1>
			<h1>This is Heading2 H1</h1>
			<h1>This is Heading3 H1</h1>
			<h2>This is Heading1 H2</h2>
			<h2>This is Heading1 H3</h2>
		<div id="dId-2">
			<button class="b1" onclick="getCountP1()">Get Paragraph Count</button>
			<span id="sid1" style="padding-left:20px;"></span><br/><br/> 
			<button class="b2" onclick="getCountH1()">Get H1 count</button>
			<span id="sid2" style="padding-left:20px;"></span><br/><br/>
			<button class="b3" onclick="getCountH2()">Get H2 count</button>
			<span id="sid3" style="padding-left:20px;"></span><br/><br/>

Output :

1. Before the executing the function

2. After the executing the function