HTML DOM Element getElementsByTagName()
Examples
Change the HTML content of the first <li> element in a list:
const list = document.getElementsByTagName("UL")[0];
list.getElementsByTagName("li")[0].innerHTML = "Milk";
Try it Yourself »
Number of <p> elements in "myDIV":
const element = document.getElementById("myDIV");
const nodes = element.getElementsByTagName("p");
let numb = nodes.length;
Try it Yourself »
Change the font size of the second <p> element in "myDIV":
const element = document.getElementById("myDIV");
element.getElementsByTagName("p")[1].style.fontSize = "24px";
Try it Yourself »
More examples below.
Definition and Usage
The getElementsByTagName()
method returns a collection of
child elements with a given tag name.
The getElementsByTagName()
method returns
a NodeList object.
NodeList
A NodeList is an array-like collection (list) of nodes.
The nodes in the list can be accessed by index. The index starts at 0.
The length Poperty returns the number of nodes in the list.
Syntax
element.getElementsByTagName(tagname)
Parameters
Parameter | Description |
tagname | Required. The tagname of the child elements. |
Return Value
Type | Description |
NodeList | The element's child elements with the given tagname. The elements are sorted as they appear in the source code. |
More Examples
Change the background color of all <p> elements inside "myDIV":
const div = document.getElementById("myDIV");
const nodes = x.getElementsByTagName("P");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "red";
}
Try it Yourself »
Change the background color of the fourth element (index 3) inside "myDIV":
const div = document.getElementById("myDIV");
div.getElementsByTagName("*")[3].style.backgroundColor = "red";
Try it Yourself »
Using the "*" parameter.
Change the background color of all elements inside "myDIV":
const div = document.getElementById("myDIV");
const nodes = div.getElementsByTagName("*");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundColor = "red";
}
Try it Yourself »
Browser Support
element.getElementsByTagName()
is supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |