Home  >  Article  >  Web Front-end  >  ## How to Modify CSS Rules with JavaScript Without Inline Styling?

## How to Modify CSS Rules with JavaScript Without Inline Styling?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 02:22:29600browse

## How to Modify CSS Rules with JavaScript Without Inline Styling?

Modifying 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn