HTML DOM getElementsByClassName() method
Example
In the list with class="example", modify the text of the first item (index value 0) with class="child":
var
list = document.getElementsByClassName(
"example"
)[
0
];
list.getElementsByClassName(
"child"
)[
0
].innerHTML =
"Milk"
;
Before modifying the text:
- Coffee
- Tea
After modifying the text:
- Milk
- Tea
Try it »
Definition and usage
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 an ordered list of nodes. With the NodeList object we can access the nodes in the list by their index number (the index starts at 0).
Tip: You can use the NodeList object'slength property to determine the number of elements with the specified class name, and loop through each element to get the one you need.
Browser support
The numbers in the table indicate the first browser version that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| getElementsByClassName() | 4.0 | 9.0 | 3.0 | 3.1 | 9.5 |
Syntax
element
.getElementsByClassName(
classname
)
Parameter value
| Parameters | Type | Description |
|---|---|---|
| classname | String | Required. The class name of the element you want to get. |
多个类名使用空格分隔,如 "test demo"。 |
Technical description
| DOM Version: | Core Level 1 Element Object |
|---|---|
| Return Value: | NodeList object, representing a collection of elements with the specified class name. The order of elements in the collection is sorted by their appearance order in the code. |
More examples
Example
Modify
var
x = document.getElementById(
"myDIV"
);
x.getElementsByClassName(
"child"
)[
1
].style.backgroundColor =
"red"
;
Try it »
Example
Check
var
x = document.getElementById(
"myDIV"
).getElementsByClassName(
"child"
).length;
x The output result is:
3
Try it »
Example
Modify the background color of the first element with class names "child" and "color" in the element with class="example":
var
x = document.getElementsByClassName(
"example"
)[
1
];
x.getElementsByClassName(
"child color"
)[
0
].style.backgroundColor =
"red"
;
Try it »
Example
Modify
var
x = document.getElementById(
"myDIV"
);
var
y = x.getElementsByClassName(
"child"
);
var
i;
for
(i =
0
; i < y.length; i++) {
y[i].style.backgroundColor =
"red"
;
}
Try it »
Related Articles
CSS Tutorial: CSS selector
CSS Reference Manual: CSS .class Selector
HTML DOM Reference Manual: document.getElementsByClassName()
HTML DOM Reference Manual: className property
HTML DOM Reference Manual: HTML DOM Style Object
Element object