getElementsByClassName

See­ing as Fire­fox 3, Safari 3.1 and Opera 9.5b now sup­port getElementsByClassName, it only seems fair to add sup­port 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 Inter­net Explorer 5.5 or below and Dillo 0.8.6. I’d change it but, to be hon­est, nobody uses Inter­net Explorer 5.5 or below any­way and Dillo hasn’t been updated in 2 years.

Some­thing like document.getElementById('content').getElementsByClassName doesn’t work in all browsers, not­ably Inter­net Explorer 6 and 7 (see com­ment by Michael and com­ment by Sid).

I should also note that it fol­lows the Moz­illa spec to the let­ter — mean­ing that document.getElementsByClassName('classOne classTwo'); will return any ele­ment with class names of both classOne and classTwo. Of course, this func­tion degrades rather nicely with newer browsers or where a getElementsByClassName func­tion has already been defined so by fol­low­ing the spec, you should get on pretty fine.

Comments

3 responses have been made so far. Add your comments.

  1. Michael said :

    Unfor­tu­n­et­ally I was unable to get this func­tion to work in either ie7 or ie6 and I can’t fig­ure out why.
    Why?

  2. IE likes to have a thing of mess­ing up everything. Admit­tedly, I only checked it with document.getElementsByClassName and not other vari­ous DOM objects (like document.getElementById('content').getElementsByClassName as an example).

    Fire­fox, Safari and Opera all work fine with both methods.

    document.getElementsByClassName works in all four browsers though.

  3. What do you think? Leave a comment...