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.
var elements = element.getElementsByClassName(names);
HTMLCollection
of found elements.Element
of a document.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'; });
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Element.getElementsByClassName()' in that specification. | Living Standard | Initial definition |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) [1] | 9 | (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 reflect the change in the spec.
[2] Safari on iOS 8 and OS X 10.10 returns a NodeList
.
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/element/getElementsByClassName