English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM getElementsByClassName() method

HTML DOM Document Object

getElementsByClassName()The method can obtain elements with the specified class attribute value, and the return value is a collection.

The elements in the returned list are sorted in the order they appear in the source code.

The returned list can be accessed by index number. The index starts from 0.

Using the arraylengthThe property determines the number of elements with the specified class name, and then all elements can be traversed to extract the required information.

Syntax:

document.getElementsByClassName(class)
var x = document.getElementsByClassName("demo");
Test and See‹/›

Browser compatibility

The getElementsByClassName() method is fully supported by all browsers:

Method
getElementsByClassName()IsIsIsIsIs

Parameter value

ParameterDescription
classA string representing the class name of the element to be obtained.
To search for multiple class names, separate them with spaces, for example, 'demo color'.

Technical details

Return value: Returns an array-like object of all child elements with the given class names.
DOM Version:DOM Level1

More Examples

Use the "demo" and "color" classes to get all elements:

var x = document.getElementsByClassName("demo color");
Test and See‹/›

Use class="demo" to change the background color of all elements:

var x = document.getElementsByClassName("demo");
for (let i = 0; i < x.length; i++) {
   x[i].style.backgroundColor = "coral";
}
Test and See‹/›

Related References

DOM Document querySelector()Methods

DOM Document querySelectorAll()Methods

DOM Document getElementById()Methods

DOM Document getElementsByTagName()Methods

HTML DOM Document Object