Blog


getElementsByClassName in Firefox 3

I've been waiting for this one for a while - and it was just committed to the Mozilla trunk yesterday:
Firefox 3 is going to have support for getElementsByClassName.

Robert Sayre just merged in his changes yesterday, taking this feature live.

If you're curious as to why this feature is being included (or where the reasoning for it originated from) - it's because it's part of the Web Applications 1.0 (HTML 5) specification. The implementation that's in Firefox is slightly different from what's presented in the specification; however, you can expect that the specification will probably be updated to reflect that changes that've been made.

getElementsByClassName has long been a mainstay of web developers everywhere - and by making it official (both in specification and in implementation), web applications are going to see a huge jump in speed.

I've pulled together some simple examples of what you can do with this new element selector.

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;
});

Some basic code can be found in the test cases for this feature. You'll need to have a nightly version of Firefox in order to run the code contained within it. I really can't wait until this is live.

Update: This post has been submitted to Digg.

Update: This function is now documented on the MDC Wiki.

Tags: javascript, traversing, whatwg, dom, getelementsbyclassname, traversal, html5

Current Projects

jQuery JavaScript Library

jQuery

Comprehensive DOM, Event, Animation, and Ajax JavaScript Library.

Recent Projects

Pro JavaScript Techniques

JavaScript Book

The best techniques for professional JavaScript. Published by Apress.


Hosting provided by the cool dudes at Engine Yard.