HTML DOM Element getElementsByClassName()
Examples
Change the text of the first list item with class="child":
list.getElementsByClassName("child")[0].innerHTML = "Milk";
Number of elements with class="child" in "myDIV":
const nodes = element.getElementsByClassName("child");
let number = nodes.length;
Change the size of the second element with class="child":
element.getElementsByClassName("child")[1].style.fontSize = 24px";
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
Parameters
The class name of the elements.
Search for multiple class names separated by spaces like "test demo".
Return Value
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":
elements.getElementsByClassName("child color")[0].style.fontSize = "24px";
Change the color of all elements in "myDIV" with class="child":
const nodes = element.getElementsByClassName("child");
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.color = "red";
}
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 |