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.
Description
The getElementsByTagName()
method returns a collection of
all child elements with a given tag name.
The getElementsByTagName()
method returns
a live HTMLCollection.
HTMLCollection
An HTMLCollection is an array-like collection (list) of HTML elements.
The length Property returns the number of elements in the collection.
The elements can be accessed by index (starts at 0).
An HTMLCollection is live. It is automatically updated when the document is changed.
Syntax
element.getElementsByTagName(tagname)
Parameters
Parameter | Description |
tagname | Required. The tagname of the elements. |
Return Value
Type | Description |
Object | An HTMLCollection object. A collection of elements with a specified tag name. The elements are sorted as they appear in the document. |
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 | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |