Forum Moderators: open

Message Too Old, No Replies

Possible to change a CSS declaration with JavaScript?

Not changing the class name, changing the dec itself

         

MichaelBluejay

6:27 am on Jun 9, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Let's say I have this definition:
.content {font:11px Verdana}


Is it possible to change the definition to something like this with JavaScript?
.content {font:12px Arial}


I know I can change the classname of objects from one class to another, but I'm wondering if there's a way to redefine a CSS declaration *directly*.

rocknbil

4:30 pm on Jun 9, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can append any current style sheets, but of course, IE has it's own way of doing things so you need two rules. So if you have say, a single style sheet

<link rel="stylesheet" type="text/css" href="/css/yourstyle.css">

This is a great way to modify output for devices that can access JS, leaving generic non JS content as a default.


<script type="text/javascript">
window.onload=function() {
if (document.styleSheets[0].cssRules) {
var oLength = document.styleSheets[0].cssRules.length;
document.styleSheets[0].insertRule('.content {font-size:12px Arial}', oLength);
}
else if (document.styleSheets[0].rules) {
var newStyle = document.createStyleSheet();
newStyle.addRule('.content' , 'font-size:12px Arial');
}
};
</script>


The first case (as I recall) is Moz/standards specific, it is actually appending any selectors in styleSheets[0], so any subsequent style sheets containing a .content selector for font-size,

<link rel="stylesheet" type="text/css" href="/css/yourstyle.css">
<link rel="stylesheet" type="text/css" href="/css/some-other-size.css"> <!-- styleSheets[1] -->

... will overwrite it. For IE, since it comes onload after the other style sheets have loaded, it's actually creating a new style sheet, so it will take precedence over any styles defined for .content, like any other subsequent style sheet would.

MichaelBluejay

1:32 pm on Jun 10, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thank you very much for the detailed answer. But I can't change a declaration dynamically then, right?

rocknbil

5:46 pm on Jun 10, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I don't think so, I recently explored this. if you dynamically create the sheets, you *might* be able to but not for "regular" sheets. But by appending to the sheet, it's the same result.

.content { font-size: 200%; color:#000; }
.content { font-size: 90%; }

The font size will be 90% of default, but still be #000, this is in effect what you're doing with the JS above, adding a "last word" in the cascade.