HTML DOM getElementsByClassName()
Method
Example
Modify the text of the first item (index value 0) with class "child" in a list with class "example":
var list = document.getElementsByClassName("example")[0];
list.getElementsByClassName("child")[0].innerHTML = "Milk";
Before modification:
CoffeeTea
After modification:
MilkTea
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 collection of nodes. We 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
Parameter Values
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, e.g., "test demo". |
Technical Details
DOM Version: | Core Level 1 Element 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
Modify the background color of the second element with class "child" in a <div>
element:
var x = document.getElementById("myDIV");
x.getElementsByClassName("child")[1].style.backgroundColor = "red";
Example
Check how many elements with class "child" are in a <div>
element (using the NodeList's length property):
var x = document.getElementById("myDIV").getElementsByClassName("child").length;
x output:
3
Example
Modify the background color of the first element with both class names "child" and "color" in an element with class "example":
var x = document.getElementsByClassName("example")[1];
x.getElementsByClassName("child color")[0].style.backgroundColor = "red";
Example
Modify the background color of all elements with class "child" in a <div>
element:
var x = document.getElementById("myDIV");
var y = x.getElementsByClassName("child");
var i;
for (i = 0; i < y.length; i++) {
y[i].style.backgroundColor = "red";
}
Related Articles
CSS Tutorial: CSS Selectors
CSS Reference: CSS .class Selector
HTML DOM Reference: document.getElementsByClassName()
HTML DOM Reference: className Property
HTML DOM Reference: HTML DOM Style Object