Home > Article > Web Front-end > How can you access and modify CSS declarations directly using JavaScript?
Accessing and Modifying CSS Declarations with JavaScript
Inline styling offers a straightforward approach to modify an element's appearance, but it can override existing CSS rules and disrupt intended behavior. To avoid this, developers can opt to modify the CSS declaration objects directly.
CSS declaration objects can be accessed through the styleSheets property of the document object. Each styleSheet object contains a collection of cssRules (or rules in Internet Explorer). These rules represent styles defined within the respective stylesheet.
To modify a CSS declaration object, retrieve the corresponding rule from the stylesheet's cssRules collection and access its style property. For instance:
<code class="javascript">var sheet = document.styleSheets[0]; var rules = sheet.cssRules || sheet.rules; rules[0].style.color = 'red';</code>
This code will modify the color declaration for the first rule in the stylesheet to 'red'.
Note that modifying the style property of a rule will override any existing declarations within that rule. To selectively modify specific properties, use the following syntax:
<code class="javascript">var sheet = document.styleSheets[0]; var rules = sheet.cssRules || sheet.rules; rules[0].style['background-color'] = 'blue';</code>
This code will only change the background-color property of the first rule.
Demonstrating this technique, the following JSFiddle shows how to modify the color of an element with a class of "box", without affecting the hover effect: http://jsfiddle.net/8Mnsf/1/
The above is the detailed content of How can you access and modify CSS declarations directly using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!