Returns a set of elements which have all 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.


elements = document.getElementsByClassName(names); // or:
elements = rootElement.getElementsByClassName(names);
  • elements is a 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'


And if we go ahead and add in JavaScript 1.6's Array extras, we can do some really-cool matches.

Find all div elements that have a class of 'test'

var tests = Array.filter( document.getElementsByClassName('test'), function(elem){
    return elem.nodeName == 'DIV';

Find all elements that have a class of 'test' (as do their parent element)

var test = document.getElementsByClassName('test');
var someTests = Array.filter( test, function(elem){
    return Array.indexOf( test, elem.parentNode ) > -1;

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 3.0 9.0 (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?


Document Tags and Contributors

 Last updated by: Anonymous,