HTML DOM getElementsByClassName()Method

Document 对象参考手册Document Object

Example

Get all elements with the specified class name:

var x = document.getElementsByClassName("example");

Try it Yourself »

Definition and Usage

The getElementsByClassName() method returns a collection of all elements with the specified class name in the document, as a NodeList object.

The NodeList object represents an ordered list of nodes. In the NodeList object, we can access the nodes in the list by their index numbers (starting from 0).

Tip:You can use the NodeList object's lengthproperty to determine the number of elements with the specified class name, and loop through the elements to get the one you need.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
getElementsByClassName() 4.0 9.0 3.0 3.1 9.5

Syntax

document.getElementsByClassName(classname)

Parameters

Parameter Type Description
classname String Required. The class name of the element(s) you want to get.

Multiple class names are separated by spaces, like "test demo".

Technical Details

DOM Version: Core Level 1 Document Object
Return Value: A NodeList object, representing a collection of elements with the specified class name. Elements are sorted in the order they appear in the code.

实例

More Examples

Example

Get all elements with class names "example" and "color", and change their color:

var x = document.getElementsByClassName("example color");

Try it Yourself »

Example

Find out how many elements with class="example" there are in the document (using the NodeList object's length property):

var x = document.getElementsByClassName("example").length;

Try it Yourself »

Example

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

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

Try it Yourself »

Related Pages

CSS Tutorial:CSS Selectors

CSS Reference:CSS .classSelectors

HTML DOM Reference:element.getElementsByClassName()

HTML DOM Reference:className Property

HTML DOM Reference:HTML DOM classList Property

HTML DOM Reference:HTML DOM Style Object


Document 对象参考手册Document Object

Other Extensions