How to Dynamically Modify CSS Declarations with JavaScript?

Patricia Arquette
Release: 2024-10-25 02:34:30
Original
815 people have browsed it

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>
    Copy after login
  2. Retrieve the CSS rules:

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

    <code class="javascript">var rule = rules[0];</code>
    Copy after login
  4. Modify the rule's styles:

    <code class="javascript">rule.style.color = 'red';</code>
    Copy after login

Example

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!