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 child elements with a given class name.

The getElementsByClassName() method returns a NodeList object.


NodeList

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.


Syntax

element.getElementsByClassName(classname)

Parameters

Parameter Description
classname Required.
The class name of the child elements.
Separate multiple names with spaces ("child color").

Return Value

Type Description
NodeListThe elements' child elements with the given class name.
The elements are sorted as they appear in the source code.


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

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.