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

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

Linda Hamilton
Release: 2024-10-25 02:22:29
Original
667 people have browsed it

## 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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template