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’

  1. document.getElementsByClassName('test')

Get all elements that have a class of ‘red’ and ‘test’

  1. document.getElementsByClassName('red test')

Get all elements that have a class of ‘test’, inside of an element that has the ID of ‘main’

  1. 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’

  1. Array.filter( document.getElementsByClassName('test'), function(elem){
  2.     return elem.nodeName == 'DIV';
  3. });

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

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

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.

Posted: February 2nd, 2007


If you particularly enjoy my work, I appreciate donations given with Gittip.

16 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

Ukiyo-e Database and Search

Ukiyo-e.org

Japanese woodblock print database and search engine.


John Resig Twitter Updates

@jeresig

Infrequent, short, updates and links.