HTML DOM Document getElementsByTagName() Method

Get all elements with the tag name li"

Definition and Usage

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 elements in a collection can be accessed by index (starts at 0).

The length Property returns the number of elements in the collection.

Syntax

document.getElementsByTagName(tagname)

Parameters

Parameter Description
tagname Required.
The tagname of the elements.

Return Value

Type Description
ObjectAn 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;

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";
}

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 IE Edge Firefox Safari Opera
Yes 9-11 Yes Yes Yes Yes