Home >Web Front-end >CSS Tutorial >How to Dynamically Modify CSS Declarations with JavaScript?

How to Dynamically Modify CSS Declarations with JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 02:34:30889browse

How to Dynamically Modify CSS Declarations with JavaScript?

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

  1. Obtain the stylesheet object:

    <code class="javascript">var sheet = document.styleSheets[0];</code>
  2. Retrieve the CSS rules:

    <code class="javascript">var rules = sheet.cssRules || sheet.rules;</code>
  3. Select the desired rule using its index:

    <code class="javascript">var rule = rules[0];</code>
  4. 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!

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