JavaScript getElementsByTagName() Method

You are Here:

JavaScript getElementsByTagName() Method

The getElementsByTagName() method returns an HTMLCollection of elements with the given tag name.

Note: When called on the document object, the complete document is searched, including the root node.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>P 1</p> <p>P 2</p> <p>P 3</p> <button onclick="myFunction()">Click Me</button> <script> function myFunction(){ var x = document.getElementsByTagName("p"); var txt = "Hello there!"; //Try to change '0' to '1' x[0].innerHTML = txt; } </script> </body> </html>

Syntax

document.getElementsByTagName(tagName)

Parameter Values

ValueTypeExplanation
tagNameRequiredThe tagname of the elements you want to get.

More Examples

In the following example, we find the length of the given tag.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>P 1</p> <p>P 2</p> <p>P 3</p> <button onclick="myFunction()">Click Me</button> <script> function myFunction(){ var x = document.getElementsByTagName("p"); x[0].innerHTML = "Tag Length : " +x.length; } </script> </body> </html>

In the following example, we will apply CSS color property to all the paragraph.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>P 1</p> <p>P 2</p> <p>P 3</p> <script> var x = document.getElementsByTagName("p"); for(var i=0; i<x.length; i++) x[i].style.color = "green"; </script> </body> </html>

In the following example, we will get all the html tags.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h2>Heading</h2> <p>Paragraph</p> <div>Div</div> <script> var x = document.getElementsByTagName("*"); x[4].style.color = "green"; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author