Snook.ca

Your Favourite getElementsByClassName

There's a variety of scripts out there for getElementsByClassName. Oddly though, the first 20 or so results from Google are confusing or completely inaccurate. So, what's your favourite getElementsByClassName script?

UPDATE:As mentioned by Cameron, the regular expression I use above may not catch every valid class name. More specifically, class names with hyphens in them causing false positives. Using Cameron's technique of '(^| )'+classname+'( |$)' should prove more reliable.

For those unsure of what it all means, in regular expression speak, \b is used to indicate word boundaries. The problem being that a search for \bhelp\b would also find help-me which isn't what we want. The ^ indicates beginning of the string, | is an OR statement and the space is, well, a space. Similar thing on the other end except the $ means match at the end of a string. Therefore, in English, find the class name if it's the first or last part of the string or if there is a space on either side of the class name (for those of you who actually use more than one class on an element).

Mats: the regex helps match against word boundaries. The problem with your function is that a search for "mydiv" would return elements "mydiv" AND "notmydiv".

flevour: mine hasn't been specifically tested in all recent browsers. Some research seemed to indicate that older versions of Safari (iirc) don't support using * with getElementsByTagName and would therefore return an empty array.

Since I'm working on a page that both a) needs to support MacIE and b) is trying to getElementsByClassName of elements that sometimes have multiple classes (e.g. sometimes just class="item" and other times class="item last"), I have been having a little trouble with the getElementsByClassNames functions I have found up till now (MacIE doesn't support the push() method).

I think a hybrid of the functions I've found here on this page (and another page) seem to have worked, though:

I haven't tested the Opera part, but I can't imagine it doing much damage.

BTW, the positioning and previewing of this comment form are awesome. Kudos!

p.s. Most posters here didn't escape the "less than" (<) in their for loops, so half of them are cut off (which is why I had to go to another site to see if these same functions were copied elsewhere).

Sorry, comments are closed for this post. If you have any further questions or
comments, feel free to send them to me directly.

Hi. My name is Jonathan Snook and this is my site. I write about what interests me, which is usually web design, development, and technology. I'm also in the middle of a food adventure.
I wrote SMACSS. I tweet. Want to learn more?