HTML DOM getElementsByClassName()
Method
Example
Get all elements with the specified class name:
var x = document.getElementsByClassName("example");
Definition and Usage
The getElementsByClassName()
method returns a collection of all elements in the document with the specified class names, as a NodeList object.
The NodeList object represents an ordered list of nodes. You can access the nodes in the NodeList by their index number (starting from 0).
Tip: You can use the length property of the NodeList object to determine the number of elements with the specified class name, and iterate through each element to get the one you need.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
getElementsByClassName() | 4.0 | 9.0 | 3.0 | 3.1 | 9.5 |
Syntax
Parameters
Parameter | Type | Description |
---|---|---|
classname | String | Required. The class name(s) of the elements you want to get. <br> <br>Multiple class names are separated by spaces, such as "test demo". |
Technical Details
DOM Version: | Core Level 1 Document Object |
---|---|
Return Value: | NodeList object, representing a collection of elements with the specified class name(s). The elements in the collection are sorted in the order they appear in the source code. |
--- | --- |
More Examples
Example
Get all elements with both "example" and "color" class names and change their color:
Example
Check how many elements have the class "example" in the document (using the NodeList's length property):
Example
Change the background color of all elements with class "example":
Related Pages
CSS Tutorial: CSS Selectors
CSS Reference: CSS .class Selector
HTML DOM Reference: element.getElementsByClassName()
HTML DOM Reference: className Property
HTML DOM Reference: HTML DOM classList Property
HTML DOM Reference: HTML DOM Style Object