If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

getElementsByClassName to call multiple classes of same name

I have several sections of content on my site that are default 'hidden' in CSS. I use the getElementById so visitors can open each section of content individually. I now would like to add the option to open ALL content at once. All sections are contained in <div> tags with the class="show". How could I do this with getElementsByClassName?

Well, we could work harder on that regular expression and correct the problem, but yeah, your CSS trick works a lot better.

FWIW, in my replacement for getElementsByClassName I simply look for the given string to be contained in the className. Yes, I know that means that looking for "one" will incorrectly find "one-active" or even "none" or "lonesome". But that just means I'm really careful about making sure my class names don't have potential problems like that.

It only fails if you use hyphens in your class names. While - and _ are technically allowed they are not compatible with all browsers. In particular using - in a class can break a lot of JavaScript references to it since it could possibly end up being treated as a minus sign and definitely gets treated as a word boundary.

Anyway if you insist on using hyphens in class names then you could replace the '\\b'+cl+'\\b' in the regexp with '(^| )'+cl+'( |$)' so that it specifically tests just for space and start/end string boundaries. Then your classes would only malfunction in the other places where JavaScript treats the hyphen differently.

even still, i think that avoiding loops is always good, avoiding hidden snags is always good, and that CSS offers more precise group definition since its CSS selectors work in IE7 without a bunch of bring-your-own code.

cheers

Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com