HTML DOM Document getElementsByClassName()
Example
Get all elements with class="example":
Get all elements with both the "example" and "color" classes:
More examples below.
Description
The getElementsByClassName() method returns a collection of elements with a specified class name(s).
The getElementsByClassName() method returns an 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.
See Also:
Syntax
Parameters
The class name of the elements.
Search for multiple class names separated by spaces like "test demo".
Return Value
A collection of elements with the specified class name.
The elements are sorted as they appear in the document.
More Examples
Number of elements with class="example":
Change the background color of all elements with class="example":
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
Related Pages
CSS Tutorial: CSS Syntax
CSS Reference: CSS .class Selector
HTML DOM Reference: element.getElementsByClassName()
HTML DOM Reference: className Property
HTML DOM Reference: classList Property
HTML DOM Reference: Style Object
Browser Support
document.getElementsByClassName() 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 |