Altering CSS Class Attributes with JavaScript

Posted Jan 8, 2004
Last Updated Nov 3, 2011

This JavaScript function will dynamically change the style information for any CSS class in a Web Page. Applying this function to a class will cause all items calling on the class to change to the updated style value. This function works even if there are multiple stylesheets referenced in the document.

Function Name: changecss(theClass,element,value)

Example of output (Assuming you have a stylesheet defining the "exampleA" and "exampleB" classes -- the following code creates the effect below):

<span class="exampleA">Example A</span> <span class="exampleB">Example B</span> <span class="exampleA">Example A</span> <input type="button" value="Change A Red" onclick="changecss('.exampleA','color','red')"/><input type="button" value="Change A Black" onclick="changecss('.exampleA','color','black')"/>

Example A

Example B

Example A

To use this function, copy this link and place it in the head of your HTML before any other JavaScript that may use it.

<script type="text/javascript" src="http://www.shawnolson.net/scripts/public_smo_scripts.js"></script>

Please include credit when using this script and read this site's Terms & Conditions before using.

This function was last updated on October 9, 2010. It has been tested and works in the following browsers:

  • Internet Explorer 6+ (Windows)
  • Firefox 3+ (Windows & Linux)
  • Google Chrome 2.0.172.33 + (Windows)
  • Safari 3.1.1 + (Windows)
  • Opera 9.64 +(Windows)

Note that I have tested these browsers on Windows; this function works in Firefox in Linux as well. I assume that the latest Mac versions work the same.

Comment

No HTML Tags are permitted.

Vikas

Mar 18, 2014

For all dynamism in style sheets, there is a new kid on the block - JS3. JavaScript Style Sheet - Instead of putting programming in CSS, it puts CSS in a programming language. Have a look, the issue being discussed here may well be solved with JS3. This would be more structured approach as well. (JFYI: I am the author of JS3.)

Shawn Olson

Mar 22, 2014

Thanks for sharing the info. It's been over a decade since this article was posted and a lot has changed, both in the technology as well as methods of solving problems. At this point, it's been years since I personally implemented a scenario that benefited from this script.

Thomas Ng

Mar 11, 2012

Thanks a lot for this javascript, it helps me a lot. But I think it's not working properly on Opera. I tried it and it didn't work.

And one more thing, I'm trying to call this function a lot of times, maybe around 10000, and some browser can't handle it.
Opera 11 : doesn't work.
IE9 : Works properly at start, but after that it's stop working anymore.
Google v17 : Work properly, but getting slower.
Mozilla v10 : The best, don't get slower at all

Am I doing it wrong ?

Shawn Olson

Mar 19, 2012

I haven't had time to test anything lately... I will look into the Opera problem later in the week. I do know it worked in Opera at some point... but it's been a while since I've tested.

As for speed... I haven't actually done a ton of speed testing. Originally I used this mainly for menu changing... but now I handle that primarily with CSS. If I cannot use CSS, I'd probably now look to a jQuery solution.

Andrew Cox

Dec 20, 2012

Hi Thomas,

The script appends a new definition of the css property to the end of the existing class without removing the old value:
document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);

It is going to get slower and break because the class will keep growing, so after you have called the function N times, for property "name", it will look something like this:

.my_class {
name: value1;
}
.my_class {
name: value2;
}
.my_class {
name: value3;
}
.my_class {
name: value4;
}
...
.my_class {
name: valueN;
}

Best,
Andrew

Shawn Olson

Dec 20, 2012

Thanks for the input. I haven't had time to look into this since the post. I will try to fix the code. It has been years since I wrote this... and off the top of my head I think there was a reason behind the appending of rules ... but if there were (and whatever it was) it is long forgotten to me.

Jason

Mar 9, 2012

maybe my browser setting are messed or I'm missing something but there isn't a function here. was the code taken down?

Shawn Olson

Mar 9, 2012

It is in the javascript file that is hilighted in red above. Hopefullay that helps.

Jason

Mar 12, 2012

little slow some days,

Thank You!!

Shawn Olson

Mar 19, 2012

No problem :)

Eric

Jan 4, 2012

Super-useful script! Many thanks!

vishal

Dec 29, 2011

SInce it is very useful but I have one query

how to access external file class and change it using this JS?

Thanks

Shawn Olson

Jan 4, 2012

I've never had a problem with the script accessing and changing the CSS from externally linked style sheets. If you are having a problem generally, please send me a link to the page. If it is a particular browser, please share the browser version and OS.

mario santini

May 17, 2011

The script worked fine for me but it fails in https. is that to be expected?

Shawn Olson

Nov 3, 2011

Yes, it fails in https because I have never added SSL to my domain. I may add that in the future.

James Matthews

Nov 8, 2010

Nice work. Keep it up. I will use this in my new website. Thank you very much.

YesHoney

Sep 28, 2010

Nice script. Saved me some time. Does it work on Safari 5 (windows XP here)

Anfernee Lo

Sep 23, 2010

That's really great~

thanks for your work~!!!

Luis Stortini

Jul 9, 2010

On activating the script Firefox throws a DOM security error. I canĀ“t find the reason. I have tried it in a much simpler page and works fine, but not in http://cvadrat.com/test.htm Please check it.

Parul Desai

May 12, 2010

Hi,



This script is fantastic. I hv two quries



1. How do i change the class property if the class is in external css file.

2. How do i change more than two property of the same class.



Awaiting Reply.

Thanks.

Parul Desai

May 12, 2010

Hi,

This script is fantastic. I have two queries



1. how do i change the class property if my class is in external css file.

2. how to change more than two property of the same class.



Awaiting reply.

Thanks.

Jon Harris

Apr 7, 2010

Hi there, I really like the idea of this script, but I'm a bit of a newb and I simply cannot work out how to get more than one property to change.



I've tried multiple actions for on clicks, I've tried multiple classes and divs and spans...been at it 3 hours now, learnt a lot along the way, but going to have to ask for help. Right now where I'm at is that I've copied your script, pasted it twice and called the second function changecss2.

So, as doing it on the same span (or div, both work the same, or rather , not) I've now got something along the lines of



function DoTheColours() {

changecss('.changebox','color','yellow');

changecss2('.changebg','background-Color','#ff0000');

}





(Note, I had to add the word THE to the on click function above to get it to post in the GB)



(EDIT: OK, I give up trying to post the code - you'll have to guess what I did. It's been 5 times now and I'm getting frustrated)



Only the FIRST of the two changecss operations will work, even when they're both called the same.



As this site is for the visually impaired, I need this simple one-click operation to switch various high-contrast modes, which require changing BOTH the background-colour AND the font colour at the same time.



Thank you!

Khaled Al Hourani

Mar 5, 2010

Very good work, it works very well, do you know how can I save the new changes back to the css file? I mean write to the css file and save the changes, so when I get back later the new styles are all there.

Hassaan Abd-ur-Razzaq

Dec 7, 2009

Will this work on Styles defined on the ppage like in blogger.





...





...

Shawn Olson

Dec 7, 2009

As long as you can add JavaScript to a web page, then yes, it will work.

Will Bradley

Aug 20, 2009

Hi,



I tried using this code to modify an imported stylesheet from another domain:

(in this case part of the stylesheet downloaded when you use the 'bing maps' API). Works fine in IE, but in firefox I get a security error:

Error: uncaught exception: [Exception... "Security error" code: "1000" nsresult: "0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)"



Do you know if there is a workaround for this? I am thinking perhaps it would be possible to clone the class into a inline stylesheet that overrides the imported one, and then modify that?

Aleksnandr Tishin

Aug 15, 2009

When I am trying something like this:

changecss('.e','display','none');

changecss('.r','display','block');

in my function, the second call seems to be not working.



P.S. Sorry for my English

manish kumar

Jul 23, 2009

can me make any change to alter whole class on click?

Lennart Moltrecht

May 31, 2009

This works fine on Firefox, but not on Google Chrome. Can you please fix that? Thanks

Shawn Olson

Jun 23, 2009

I have updated the function. It now works in Google Chrome.

jacob

Aug 26, 2010

well, this is a tutorial, he's not writing it for a script-kiddie, as you make yourself abundantly clear. You're not his QA dept. write it yourself.

hariharadeep m

Jul 28, 2008

Let me know how to change the back groung image of a button on hover in li of css.

Shawn Olson

May 20, 2008

I have just updated the script to add rules when the properties you want to set are not in the CSS. This may have been your problem when setting values with a dash. However, I could not replicate the dash problem in IE7 or Firefox 2. Could you let me know what browser and version is having that problem?

Reinier Post

Jul 4, 2008

The problem is that CSS properties with a dash are spelled differently as Javascript DOM .style properties, e.g. background-color corresponds to .style.backgroundColor, so you have to insert a conversion function before you get or set the DOM property. This is true for at least IE 7 and Firefox 2.

Kurt Munro

Jan 10, 2009

Had major issues with this, then realised it's because you missed the // after http:// in the javascript src link...

Shawn Olson

Jan 10, 2009

Thanks for pointing that out. The&nbsp;double slashes are being stripped from the HTML in the server script... so for the moment the problem will persist until I can get a moment to&nbsp;fix the bug.&nbsp;

Brian H

May 20, 2008

Your script doesn't seem to work on any CSS properties that contain a dash (background-color, z-index, border-bottom-color, etc). Is there any specific reason for this? I'd like to be able to use this nice, simple script to move around the z-index of certain elements on a page.

Gliktch Media

Nov 6, 2009

(Replying to Brian H)



When using Javascript to modify/read a z-index, you have to use "zIndex" instead. I'm guessing the other properties you mentioned (pretty much anything with a hyphen or dash in it) would have a similar counterpart. This is so the function can differentiate between something like this:



variable1-variable2+variable3

and

variable-with-dashes



Capiche? ;)

Gary E

Nov 30, 2007

Safari 3.0.4 for PC (possibly all versions) does not seem to include any class names that are not totally lowercase. Opera needs different DOM sniffing code, see my reply to Opera observation below for pointer to patched code.

Thanks to JeroenH.

Simon Wilsher

Oct 26, 2007

changecss doesn't appear to work in Opera 9.24

Gary E

Nov 30, 2007

I asked about this in Opera's cross browser forum and somebody posted a fix there. The browser's DOM sniffing is incomplete in the script. Perhaps it can be updated here for others who have the problem?



http://my.opera.com/community/forums/topic.dml?id=214930&t=1196433894&page=1#comment2344825

Dag Fredrik

May 30, 2008

Doesn't work in Opera because Opera expects the cssRules variable to be equal to 'cssRules', and not 'rules'...

chris tillam

Jul 2, 2007

Oops, lost first line:



This is much much simpler: I found it by looking for a script that changes class, search on "js foo" for the credit:



function whatever() {

for (i=0;i

chris tillam

Jul 2, 2007

This is much much simpler: I found it by looking for a script that changes class, search on "js foo" for the credit:



function whatever()

if (document.getElementsByTagName("div").item(i).className == "yin _6")

{document.getElementsByTagName("div").item(i).style.visibility = "hidden";}



cheers

Lya santoso

Feb 18, 2007

Hi,I just want to ask, can I change css with id (not class) here? I got problem and cant solve it until now (for a reason I cant change it to class)

Parul Desai

May 12, 2010

Yes you can use this script to change for ID



If you ID is #changebox



use #changebox instead of .changebox in below line



changecss('.changebox','color','yellow');



Brian French

Feb 6, 2007

i cane across an issue with the changecss function. If the style element doesn't exist on one of the stylesheets, then it wont set it. I found the setProperty() method that will create the element if it doesnt exist. see this page (3/4 down): http://www.howtocreate.co.uk/tutorials/javascript/domstylesheets

Shawn Olson

Dec 21, 2006

Sorry... this example was not working for a while because the corresponding entry in the stylesheet was missing after an update sometime in the last few months. The example now works.

vee Jay

Feb 15, 2011

Hey man nice work keep posting such good work three cheers foe you ....

Justin Halsall

Dec 21, 2006

Doesn't work in Firefox 2

Udo Willers

Dec 30, 2006

It works in my Firefox 2.0.0.1

Alex Egg

Feb 2, 2007

Yeah, I'm having trouble with it too...
Sky Writer

Newsletter Subscription