Home >Web Front-end >CSS Tutorial >## How to Modify CSS Rules with JavaScript Without Inline Styling?
It is sometimes necessary to modify CSS declarations dynamically without resorting to inline styling. Consider the following example:
<code class="html"><style> .box {color:green;} .box:hover {color:blue;} </style> <div class="box">TEXT</div></code>
This produces a blue box that turns green on hover. However, inline styling can override this behavior:
<code class="html"><div class="box" style="color:red;">TEXT</box></code>
In this case, the box will always be red, regardless of the hover state.
To avoid this issue, you can modify the CSS declaration object directly. Here's how:
<code class="javascript">var sheet = document.styleSheets[0]; var rules = sheet.cssRules || sheet.rules; rules[0].style.color = 'red';</code>
Note that Internet Explorer uses rules instead of cssRules.
Here's a demo: [Fiddle](http://jsfiddle.net/8Mnsf/1/)
The above is the detailed content of ## How to Modify CSS Rules with JavaScript Without Inline Styling?. For more information, please follow other related articles on the PHP Chinese website!