Change the text of the first list item with class="child":
const list = document.getElementsByClassName("example")[0];
list.getElementsByClassName("child")[0].innerHTML = "Milk";
Try it Yourself »
Number of elements with class="child" in "myDIV":
const element = document.getElementById("myDIV");
const nodes = element.getElementsByClassName("child");
let number = nodes.length;
Try it Yourself »
Change the size of the second element with class="child":
const element = document.getElementById("myDIV");
element.getElementsByClassName("child")[1].style.fontSize = 24px";
Try it Yourself »
More examples below.
The getElementsByClassName()
method returns a collection of child elements with a given class name.
The getElementsByClassName()
method returns a NodeList object.
A NodeList is an array-like collection (list) of nodes.
The nodes in the list can be accessed by index. The index starts at 0.
The length Poperty returns the number of nodes in the list.
element.getElementsByClassName(
classname)
Parameter | Description |
classname | Required. The class name of the child elements. Separate multiple names with spaces ("child color"). |
Type | Description |
NodeList | The elements' child elements with the given class name. The elements are sorted as they appear in the source code. |
Change the size of the first element with "child" and "color" classes inside the second element with class="example":
const elements = document.getElementsByClassName("example")[1];
elements.getElementsByClassName("child color")[0].style.fontSize = "24px";
Try it Yourself »
Change the color of all elements in "myDIV" with class="child":
const element = document.getElementById("myDIV");
const nodes = element.getElementsByClassName("child");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.color = "red";
}
Try it Yourself »
element.getElementsByClassName()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!