Get all elements with the specified class name:
More "Try it Yourself" examples below.
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.
The numbers in the table specifies the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
getElementsByClassName() | 4.0 | 9.0 | 3.0 | 3.1 | 9.5 |
Parameter | Type | Description |
---|---|---|
classname | String | Required. The class name of the elements you want to get. To search for multiple class names, separate them with spaces, like "test demo". |
DOM Version: | Core Level 1 Document Object |
---|---|
Return Value: | A NodeList object, representing a collection of elements with the specified class name. The elements in the returned collection are sorted as they appear in the source code. |
Get all elements with both the "example" and "color" classes:
Find out how many elements with class="example" there are in the document (using the length property of the NodeList object):
Change the background color of all elements with class="example":
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