DOM:document.getElementsByClassName
From MDC
This article covers features introduced in Firefox 3
Contents |
[edit] Summary
Returns a set of elements with the given class name. 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 under the specified root element with the given class name.
[edit] Syntax
elements = document.getElementsByClassName(name) // or: elements = rootElement.getElementsByClassName(name)
-
elementsis a liveNodeListof found elements in the order they appear in the tree. -
nameis a string representing a classname of the elements. - 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.
[edit] Examples
Get all elements that have a class of 'test'
document.getElementsByClassName('test')
Get all elements that have a class of 'red' and 'test'
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')
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'
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');
Array.filter( test, function(elem){
return Array.indexOf( test, elem.parentNode ) > -1;
});