Table of contents

  1. 1. Summary
  2. 2. Syntax
  3. 3. Examples
  4. 4. Specification
Table of contents
  1. 1. Summary
  2. 2. Syntax
  3. 3. Examples
  4. 4. Specification

This content covers features introduced in Firefox 3.

« Gecko DOM Reference


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 live NodeList (but see the note below) of found elements in the order they appear in the tree.
  • 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.
Note: While the W3C specification says elements is a NodeList, this method returns a HTMLCollection both in Gecko and Internet Explorer. Opera returns a NodeList, but with a namedItem method implemented, which makes it similar to a HTMLCollection. As of January 2012, only in WebKit browsers is the returned value a pure NodeList. See bug 14869 for details.


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;

Tags (4)

Edit tags

Attachments (0)


Attach file