Element.getElementsByClassName()

The Element.getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.

Similarly the method Document.getElementsByClassName() acts on the whole document; it will return elements which are descendants of the specified document root element with the given class names.

Syntax

var elements = element.getElementsByClassName(names);
  • elements is a live HTMLCollection of found elements.
  • names is a string representing the list of class names to match; class names are separated by whitespace
  • element is any Element of a document.

Examples

Get all elements that have a class of test:

element.getElementsByClassName('test');

Get all elements that have both the red and test classes:

element.getElementsByClassName('red test');

Get all elements that have a class of test, inside of an element that has the id of main:

document.getElementById('main').getElementsByClassName('test');

We can also use methods of Array.prototype on any HTMLCollection by passing the HTMLCollection as the method's this value. Here we'll find all <div> elements that have a class of test:

var testElements = document.getElementsByClassName('test');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
    return testElement.nodeName === 'div';
});

Specifications

Specification Status Comment
DOM
The definition of 'Element.getElementsByClassName()' in that specification.
Living Standard Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) [1] (Yes) (Yes) (Yes) [2]
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? [1] ? ? ?

[1] Prior to Firefox 19, this method was returning a NodeList; it was then changed to reflects the change in the spec.

[2] Safari on iOS 8 and OS X 10.10 returns a NodeList.

Document Tags and Contributors

Contributors to this page: Jeremie, FWest98, bergus, fscholz, teoli, kscarfone, nairakhil13, Sheppy, fredy, Brettz9
Last updated by: Jeremie,
Hide Sidebar