Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML DOM getElementsByClassName() method

HTML DOM getElementsByClassName() method

Document Object Reference Document Object

Example

Get all elements with the specified class name:

var

x = document.getElementsByClassName(

"example"

);

Try it »


Definition and usage

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

The NodeList object represents an ordered list of nodes. With the NodeList object we can access the nodes in the list by their index number (the index starts at 0).

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


Browser support

The numbers in the table indicate the first browser version that supports this method.

Method
getElementsByClassName() 4.0 9.0 3.0 3.1 9.5

Syntax

document.getElementsByClassName(

classname

)

Parameters

Parameters Type Description
classname String Required. The class name of the element you want to get.
 多个类名使用空格分隔,如 "test demo"。 |

Technical description

DOM version: Core Level 1 Document Object
Return Value: NodeList object, representing a collection of elements with the specified class name. The order of elements in the collection is sorted by their appearance order in the code.

More examples

Example

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

var

x = document.getElementsByClassName(

"example color"

);

Try it »

Example

Check how many elements with the style class="example" are in the document (using the length property of the NodeList object):

var

x = document.getElementsByClassName(

"example"

).length;

Try it »

Example

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

var

x = document.getElementsByClassName(

"example"

);

var

i;

for

(i =

0

; i < x.length; i++) {

    x[i].style.backgroundColor =

"red"

;

}

Try it »


Related pages

CSS Tutorial: CSS selector

CSS Reference Manual: CSS .class Selector

HTML DOM Reference Manual: element.getElementsByClassName()

HTML DOM Reference Manual: className property

HTML DOM Reference Manual: HTML DOM classList property

HTML DOM Reference Manual: HTML DOM Style Object


Document Object Reference Document Object