HTML DOM Document getElementsByClassName() method

Definition and Usage

getElementsByClassName() The method returns a collection of elements with the specified class name.

getElementsByClassName() The method returns HTMLCollection.

getElementsByClassName() Properties are read-only.

HTMLCollection

HTMLCollection Is a collection of HTML elements similar to an array (list).

Elements in the collection can be accessed by index (starting from 0).

length Property returns the number of elements in the collection.

See also:

getElementById() method

getElementsByTagName() method

querySelector() method

querySelectorAll() method

HTMLCollection object

Instance

Example 1

Get all elements with class="example":

const collection = document.getElementsByClassName("example");

Try It Yourself

Example 2

Get all elements that have both the "example" and "color" classes:

const collection = document.getElementsByClassName("example color");

Try It Yourself

Example 3

Number of elements with class="example":

let numb = document.getElementsByClassName("example").length;

Try It Yourself

Example 4

Change the background color of all elements with class="example":

const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
  collection[i].style.backgroundColor = "red";
}

Try It Yourself

Syntax

document.getElementsByClassName("classname)

Parameter

Parameter Description
classname

Required. The class name of the element.

Retrieve multiple class names separated by spaces, for example "test demo".

Return Value

Type Description
Object

HTMLCollection Object.

A collection of elements with the specified class name.

Sorts elements in the order they appear in the document.

Browser Support

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

All Browsers Support It:

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

Related Pages

CSS Tutorial:CSS Syntax

CSS Reference Manual:CSS .class Selector

HTML DOM Reference Manual:element.getElementsByClassName()

HTML DOM Reference Manual:className Attribute

HTML DOM Reference Manual:classList Attribute

HTML DOM Reference Manual:Style Object