Seeing as Firefox 3, Safari 3.1 and Opera 9.5b now support getElementsByClassName, it only seems fair to add support for older browsers, thus enabling proper use of it.
Object.prototype.getElementsByClassName = document.getElementsByClassName = document.getElementsByClassName || function(className) {
className = className.replace(/\s+/g, ' ').replace(/^\s|![A-Za-z0-9-_\s]|\s$/g, '').split(' ');
for (var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b = [], classNameLength = className.length, passed = true; i < elementsLength; i++, passed = true) {
for (var j = 0; j < classNameLength && passed; j++) {
passed = (new RegExp('(^|\\\s)' + className[j] + '(\\\s|$)', 'i')).test(elements[i].className);
}
if (passed) {
b.push(elements[i]);
}
}
return b;
};
document.getElementsByClassName works in the 30+ browsers that I’ve tested, apart from Internet Explorer 5.5 or below and Dillo 0.8.6. I’d change it but, to be honest, nobody uses Internet Explorer 5.5 or below anyway and Dillo hasn’t been updated in 2 years.
Something like document.getElementById('content').getElementsByClassName doesn’t work in all browsers, notably Internet Explorer 6 and 7 (see comment by Michael and comment by Sid).
I should also note that it follows the Mozilla spec to the letter — meaning that document.getElementsByClassName('classOne classTwo'); will return any element with class names of both classOne and classTwo. Of course, this function degrades rather nicely with newer browsers or where a getElementsByClassName function has already been defined so by following the spec, you should get on pretty fine.
Comments
3 responses have been made so far. Add your comments.
Unfortunetally I was unable to get this function to work in either ie7 or ie6 and I can’t figure out why.
Why?
IE likes to have a thing of messing up everything. Admittedly, I only checked it with
document.getElementsByClassNameand not other various DOM objects (likedocument.getElementById('content').getElementsByClassNameas an example).Firefox, Safari and Opera all work fine with both methods.
document.getElementsByClassNameworks in all four browsers though.