HTML DOM Element getElementsByClassName()
Examples
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.
Description
The getElementsByClassName()
method returns a collection of
all child elements with a given class name.
The getElementsByClassName()
method returns a live HTMLCollection.
HTMLCollection
An HTMLCollection is an array-like collection (list) of HTML elements.
The length Property returns the number of elements in the collection.
The elements can be accessed by index (starts at 0).
An HTMLCollection is live. It is automatically updated when the document is changed.
Syntax
element.getElementsByClassName(classname)
Parameters
Parameter | Description |
classname | Required. The class name of the elements. Search for multiple class names separated by spaces like "test demo". |
Return Value
Type | Description |
Object. | An HTMLCollection object. A collection of elements with the specified class name. The elements are sorted as they appear in the document. |
More Examples
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 »
Browser Support
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 |