HTML DOM Element getElementsByClassName() method

Definition and Usage

getElementsByClassName() The method returns a collection of child elements with the given class name, as a NodeList object.

See also:

classList attribute

className attribute

querySelector() method

querySelectorAll() method

getElementsByTagName() method

HTML DOM Style Object

Tutorial:

CSS Syntax

CSS Selector

CSS Selector Reference Manual

NodeList

NodeList Is a node collection (list) similar to an array.

You can access nodes in the list by index (index). The index starts from 0.

length attributeReturns the number of nodes in the list.

Instance

Example 1

Use class="child" to change the text of the first list item:

const list = document.getElementsByClassName("example")[0];
list.getElementsByClassName("child")[0].innerHTML = "Milk";

Try it yourself

Example 2

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

Example 3

Change the size of the second element of class="child":

const element = document.getElementById("myDIV");
element.getElementsByClassName("child")[1].style.fontSize = 24px";

Try it yourself

Example 4

Use the "child" and "color" classes in the second element with class="example" to change the size of the first element:

const elements = document.getElementsByClassName("example")[1];
elements.getElementsByClassName("child color")[0].style.fontSize = "24px";

Try it yourself

Example 5

Change the color of all elements with class="child" in "myDIV":

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

Syntax

element.getElementsByClassName(classname)

Parameter

Parameter Description
classname

Required. The class name of the child element.

Multiple names are separated by spaces (e.g., "child color").

Return value

Type Description
NodeList

Child elements that contain elements with the given class name.

Elements are sorted in the order they appear in the source code.

Browser support

element.getElementsByClassName() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support