Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify a css rule object with javascript [duplicate]

Possible Duplicate:
Changing a CSS rule-set from Javascript

I was wondering if there is any possibility to modify Css stylesheet declarations without going for inline styling.

Here is a quick example :

<style>
    .box {color:green;}
    .box:hover {color:blue;}
</style>

<div class="box">TEXT</div>

That gives a blue written box that turns green written on hover.

If I give inline styling for the color, the hover behavior will be lost :

<div class="box" style="color:red;">TEXT</box>

That gives a red written box, no matter what.

So my question is, how can one access and modify the css declaration object rather than overwriting styles with inline ones.

Thanks,

like image 214
jonBreizh Avatar asked Nov 23 '12 11:11

jonBreizh


People also ask

Can you modify CSS with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

How do I change dynamic property in CSS?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.

How do I change CSS runtime?

You could change it any of the following ways: Adding a style declaration in the page. Adding an inline style declaration on the element. Using jQuery to change the style of the element.

Can we include CSS in JavaScript?

JavaScript can also be used to load a CSS file in the HTML document.


1 Answers

You could use the cssRules on the DOM stylesheet object corresponding to your original stylesheet to modify your rule.

var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;

rules[0].style.color = 'red';

Note that IE uses rules instead of cssRules.

Here is a demonstration: http://jsfiddle.net/8Mnsf/1/

like image 105
Asad Saeeduddin Avatar answered Sep 21 '22 05:09

Asad Saeeduddin