The getElementsByClassName method of Document interface 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);
  • 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
  • getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.


Get all elements that have a class of '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':


Get the first element with a class of 'test', or undefined if there is no matching element:


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 =, function(testElement){
  return testElement.nodeName === 'DIV';

Get the first element whose class is 'test'

This is the most commonly used method of operation.

    <div id="parent-id">
        <p>hello world 1</p>
        <p class="test">hello world 2</p>
        <p>hello world 3</p>
        <p>hello world 4</p>

        var parentDOM = document.getElementById("parent-id");
        var test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself
        console.log(test); //HTMLCollection[1]

        var testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted
        console.log(testTarget); //<p class="test">hello world 2</p>


Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support YesEdge Full support YesFirefox Full support 4IE Full support 9Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android ?


Full support  
Full support
Compatibility unknown  
Compatibility unknown