Access and Modify CSS Declarations with JavaScript
To modify CSS declarations dynamically, without resorting to inline styling, access the CSS rule-set object from the DOM stylesheet.
How to Modify CSS Declarations
Obtain the stylesheet object:
<code class="javascript">var sheet = document.styleSheets[0];</code>
Retrieve the CSS rules:
<code class="javascript">var rules = sheet.cssRules || sheet.rules;</code>
Select the desired rule using its index:
<code class="javascript">var rule = rules[0];</code>
Modify the rule's styles:
<code class="javascript">rule.style.color = 'red';</code>
Example
Consider the following example:
<code class="html"><style> .box {color: green;} .box:hover {color: blue;} </style> <div class="box">TEXT</div></code>
To change the text color of .box to red, without affecting the hover behavior:
<code class="javascript">var sheet = document.styleSheets[0]; var rules = sheet.cssRules || sheet.rules; rules[0].style.color = 'red';</code>
Note for Internet Explorer
Internet Explorer uses rules instead of cssRules to access the CSS rules.
Demonstration
A live demonstration of accessing and modifying CSS declarations with JavaScript can be found at: http://jsfiddle.net/8Mnsf/1/
The above is the detailed content of How to Dynamically Modify CSS Declarations with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!