Returns an array-like object of 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. You may also call getElementsByClassName()
on any element; it will return only elements which are descendants of the specified root element with the given class names.
var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names);
HTMLCollection
of found elements.Get all elements that have a class of 'test'
document.getElementsByClassName('test');
Get all elements that have both the 'red' and 'test' classes
document.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'; });
This is the most commonly used method of operation
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="parent-id"> <p>hello word1</p> <p class="test">hello word2</p> <p >hello word3</p> <p>hello word4</p> </div> <script> var parentDOM = document.getElementById("parent-id"); var test=parentDOM.getElementsByClassName("test");//test is not target element console.log(test);//HTMLCollection[1] var testTarget=parentDOM.getElementsByClassName("test")[0];//year , this element is target console.log(testTarget);//<p class="test">hello word2</p> </script> </body> </html>
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 3.0 | 9.0 | (Yes) | (Yes) |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | (Yes) | ? | ? | ? | ? |
© 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/document/getElementsByClassName