The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

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.

Changing All Instances of a CSS Class

Hello,
I'm wondering how I could change the style attributes of all instances of a class on my page using Javascript, so that I can hide multiple divs on my page that have the "detail_box" class. I tried using this, but it didn't work when I tried it on IE 6. Does anyone know of a cross-browser way to do this?

Thanks,
but that doesn't seem to be working for me. The error I get says "document.stylesheets.0 is not an object". Could this possibly have something to do with using an @import statement to load my stylesheet?

It will also work better if you give your @import an ID, rather than calling it by its index on the page.

Here's some sample code to start you off. Let's say you want to change all instances of the <h3> tag, and you have a rule saying that all <h3>s should be red in your external sheet, and you want to change that to blue:

the stylesheets name is styles.css but you are trying to call myStyles.css . I think you need to rename your stylesheet or change document.styleSheets['myStyles']... to document.styleSheets['styles']...

I could be completely wrong but I thought I'lld give it a go at helping you

so if you - alert(document.styleSheets[0].rules[0].selectorText) - it will return ".class1"

to change a property within that style - document.styleSheets[0].rules[0].style.color='red'

This is a powerfull way to do things, and opens allot of possibilities, but its use is limited with browsers other then IE5+. IE4 , and NS6+ has some support for this, but its buggy at best. And note you'll need to write separate codes for NS6, and to this point I havent had any success, but I haven't downloaded a new copy of NS6 for sometime.

Look at www.w3.org's DOM2 Style and CSS interfaces to see how you would accomplish the same in Moz. IE is surprisingly close to the DOM2 standard for once, but still different enough to require different code for it and standards-compliant browsers.