HTML DOM getElementsByTagName() Method
The HTML DOM getElementsByTagName() method in HTML returns the collection of all the elements in the document with the given tag name. To extract any info just iterate through all the elements using the length property.
Syntax:
var elements = document.getElementsByTagName(name);
Parameters:
- elements is a collection of all the found elements in the order they appear with the given tag name.
- name is a string representing the name of the elements. The special string “*” represents all elements.
Example 1: In this example, we will change the background color of the element using document.getElementByTagName() function.
html
< body style = "text-align: center" > < h1 style = "color: green;" > GeeksforGeeks </ h1 > < h2 > DOM getElementsByTagName() </ h2 > < p >A computer science portal for geeks.</ p > < button onclick = "geek()" >Try it</ button > < script > function geek() { var doc = document.getElementsByTagName("p"); doc[0].style.background = "green"; doc[0].style.color = "white"; } </ script > </ body > |
Output:

Example 2: In this example, we will change the properties of multiple elements using document.getElementsByTagName() function.
html
< body style = "text-align: center" > < h2 style = "color: green;" > DOM getElementsByTagName() </ h2 > < p >This is the first paragraph.</ p > < p >This is the second paragraph.</ p > < p >This is the third paragraph.</ p > < button onclick = "geek()" >Try it</ button > < script > function geek() { var doc = document.getElementsByTagName("P"); var i; for (i = 0; i < doc.length ; i++) { doc[i] .style.backgroundColor = "green" ; doc[i] .style.color = "white" ; } } </script> </ body > |
Output:

We have a complete list of HTML DOM methods, to check those please go through this HTML DOM Object Complete reference article.
Supported Browsers: The browser supported by the getElementsByTagName() method are listed below:
- Google Chrome 1.0
- Edge 12.0
- Internet Explorer 5.0
- Firefox 1.0
- Opera 5.1
- Safari 1.0
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Please Login to comment...