Naši dobrovolníci ještě tento článek do jazyka Čeština nepřeložili. Přidejte se a pomozte nám tuto práci dokončit!
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] | 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
.