HTML DOM getElementsByClassName()Method

元素对象参考手册Element Object

Example

In the list with class="example", modify the text of the first item (index 0) with class="child":

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

Before modifying the text:

  • Coffee
  • Tea

After modifying the text:

  • Milk
  • Tea

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.

A NodeList object represents an ordered list of nodes. We can access the nodes in the NodeList object through the node index numbers in the list (index numbers start at 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 indicate the first browser version that fully supports the method.

Method
getElementsByClassName() 4.0 9.0 3.0 3.1 9.5

Syntax

element.getElementsByClassName(classname)

Parameter Values

Parameter Type Description
classname String Required. The class name of the element you need to get.

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

Technical Details

DOM Version: Core Level 1 Element Object
Return Value: A NodeList object, representing a collection of elements with the specified class name. The elements are ordered as they appear in the code.

Examples

More Examples

Example

Change the background color of the second element with class="child" in the <div> element:

var x = document.getElementById("myDIV");
x.getElementsByClassName("child")[1].style.backgroundColor = "red";

Try it Yourself »

Example

Count how many elements with class="child" are in the <div> element (using the length property of NodeList):

var x = document.getElementById("myDIV").getElementsByClassName("child").length;

xThe output result is:

3

Try it Yourself »

Example

Change the background color of the first element with class names "child" and "color" within the class="example" element:

var x = document.getElementsByClassName("example")[1];
x.getElementsByClassName("child color")[0].style.backgroundColor = "red";

Try it Yourself »

Example

Change the background color of all elements with class="child" in the <div> element:

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

Try it Yourself »

Related Articles

CSS Tutorial:CSS Selectors

CSS Reference:CSS .classSelectors

HTML DOM Reference:document.getElementsByClassName()

HTML DOM Reference:className Property

HTML DOM Reference:HTML DOM Style Object


元素对象参考手册Element Object

Other Extensions