Changing CSS Values with Javascript

Coltin picture Coltin · Feb 19, 2009 · Viewed 225.9k times · Source

It's easy to set inline CSS values with javascript. If I want to change the width and I have html like this:

<div style="width: 10px"></div>

All I need to do is:

document.getElementById('id').style.width = value;

It will change the inline stylesheet values. Normally this isn't a problem, because the inline style overrides the stylesheet. Example:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId"></div>

Using this Javascript:

document.getElementById('tId').style.width = "30%";

I get the following:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId" style="width: 30%";></div>

This is a problem, because not only do I not want to change inline values, If I look for the width before I set it, when I have:

<div id="tId"></div>

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value), getting back Null when I expect the string "50%" doesn't really work.

So my question: I have values in a CSS style that are not located inline, how can I get these values? How can I modify the style instead of the inline values, given an id?

Answer

Mike picture Mike · Feb 19, 2009

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.

Here is the summary:

You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

Let me know how this works for ya, and please comment if you see any errors.