HTML DOM getElementsByClassName()Method
Example
In the list with class="example", modify the text of the first item (index 0) with class="child":
list.getElementsByClassName("child")[0].innerHTML = "Milk";
Before modifying the text:
- Coffee
- Tea
After modifying the text:
- Milk
- Tea
Try it Yourself »
Definition and Usage
The getElementsByClassName() method returns a collection of all elements with the specified class name in the document, as a NodeList object.
A NodeList object represents an ordered list of nodes. We can access the nodes in the NodeList object through the node index numbers in the list (index numbers start at 0).
Tip:You can use the NodeList object's lengthproperty to determine the number of elements with the specified class name, and loop through the elements to get the one you need.
Browser Support
The numbers in the table indicate the first browser version that fully supports the method.
| Method | |||||
|---|---|---|---|---|---|
| getElementsByClassName() | 4.0 | 9.0 | 3.0 | 3.1 | 9.5 |
Syntax
Parameter Values
| Parameter | Type | Description |
|---|---|---|
| classname | String | Required. The class name of the element you need to get. Multiple class names are separated by spaces, e.g., "test demo". |
Technical Details
| DOM Version: | Core Level 1 Element Object |
|---|---|
| Return Value: | A NodeList object, representing a collection of elements with the specified class name. The elements are ordered as they appear in the code. |
More Examples
Example
Change the background color of the second element with class="child" in the <div> element:
x.getElementsByClassName("child")[1].style.backgroundColor = "red";
Try it Yourself »
Example
Count how many elements with class="child" are in the <div> element (using the length property of NodeList):
xThe output result is:
Try it Yourself »
Example
Change the background color of the first element with class names "child" and "color" within the class="example" element:
x.getElementsByClassName("child color")[0].style.backgroundColor = "red";
Try it Yourself »
Example
Change the background color of all elements with class="child" in the <div> element:
var y = x.getElementsByClassName("child");
var i;
for (i = 0; i < y.length; i++) {
y[i].style.backgroundColor = "red";
}
Try it Yourself »
Related Articles
CSS Tutorial:CSS Selectors
CSS Reference:CSS .classSelectors
HTML DOM Reference:document.getElementsByClassName()
HTML DOM Reference:className Property
HTML DOM Reference:HTML DOM Style Object
Other Extensions
Element Object