HTML DOM Document getElementsByClassName()
Example
Get all elements with class="example":
const collection = document.getElementsByClassName("example");
Try it Yourself »
Get all elements with both the "example" and "color" classes:
const collection = document.getElementsByClassName("example color");
Try it Yourself »
More examples below.
Description
The getElementsByClassName()
method returns a collection of elements with a specified class name(s).
The getElementsByClassName()
method returns an HTMLCollection.
The getElementsByClassName()
property is read-only.
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.
See Also:
Syntax
document.getElementsByClassName(classname)
Parameters
Parameter | Description |
classname | Required. The class name of the elements. Search for multiple class names separated by spaces like "test demo". |
Return Value
Type | Description |
Object. | An HTMLCollection object. 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":
let numb = document.getElementsByClassName("example").length;
Try it Yourself »
Change the background color of all elements with class="example":
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
Try it Yourself »
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 |