HTML DOM Document getElementsByTagName()
Example
Get all elements with the tag name "li":
const collection = document.getElementsByTagName("li");
Try it Yourself »
Get all elements in the document:
const collection = document.getElementsByTagName("*");
Try it Yourself »
Change the inner HTML of the first <p> element in the document:
document.getElementsByTagName("p")[0].innerHTML = "Hello World!";
Try it Yourself »
More examples below.
Description
The getElementsByTagName()
method returns a collection of all elements with a specified tag name.
The getElementsByTagName()
method returns an HTMLCollection.
The getElementsByTagName()
property is read-only.
Note
getElementsByTagName("*")
returns all elements in the document.
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.
See Also:
Syntax
document.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
The number of <li> elements in the document:
let numb = document.getElementsByTagName("li").length;
Try it Yourself »
Change the background color of all <p> elements:
const collection = document.getElementsByTagName("P");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
Try it Yourself »
Related Pages
JavaScript Reference: element.getElementsByTagName()
JavaScript Tutorial: JavaScript HTML DOM Node List
Browser Support
document.getElementsByTagName()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |