getElementsByClassName()?

© 2011, Martin Rinehart

Yes, a very reasonable thing to do. I want to highlight a bunch of ids in the source code (which is text, displayed in a div). Having taken care to assign them all to a class, I get all the elements of that class and change the background to fuchsia (or some other highly visible color that suits my mood). Simple, right?

Well, W3C has not specified a getElementsByClassName() method. Guess who has not implemented it (through IE8)? So instead of moving my article toward completion, I've dropped three steps backward to add a library routine that gets element by className:

/** Return an array of all elements in a class. */
function get_elements_by_class_name( class_name ) {
    if ( document.getElementsByClassName ) {
        return nodelist2array( document.getElementsByClassName(class_name) );
    } else {
        var elems = document.getElementsByTagName( '*' );
        var arr = [];
        for ( var i in elems ) {
            var re = new RegExp( '\\b' + class_name + '\\b' );
            if ( elems[i].className && elems[i].className.match(re) ) {
                arr.push( elems[i] );
            }
        }
        return arr;
    }
} // end: get_elements_by_class_name()

It's now 9:10 AM. I am almost where I wanted to be at 6:00 AM. While I'm in a good mood, let me ask about that NodeList. It has never once helped me—it has often been in the way. Couldn't we just have an array? And what about that stupid arguments pseudo-array? Couldn't we just have an array? Is ECMA 262 your friend? Is W3C your friend?

Feedback: MartinRinehart at gmail dot com

# # #