Home >Web Front-end >JS Tutorial >How Can I Modify CSS Stylesheet Values with JavaScript?

How Can I Modify CSS Stylesheet Values with JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 04:38:03664browse

How Can I Modify CSS Stylesheet Values with JavaScript?

Accessing and Modifying CSS Styles with JavaScript

When modifying CSS styles using JavaScript, it's crucial to target the correct elements and values. Inline CSS values can be easily changed, but obtaining and modifying values defined within the stylesheet can be challenging.

Accessing CSS Stylesheet Values

To access CSS stylesheet values given an id, follow these steps:

  1. Retrieve all stylesheets using document.styleSheets.
  2. Determine the desired stylesheet based on its href property.
  3. Obtain the array of rules (e.g., cssRules in most browsers, rules in IE).
  4. Identify the specific rule using its selectorText property.

Modifying CSS Stylesheet Values

Once the desired rule is identified, you can modify it:

  1. Set the selectorText property to change the selector (e.g., from #tId to #newId).
  2. Set the value property to change the CSS value (e.g., from width: 50% to width: 30%).

Example

In the scenario provided:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId"></div>

You can use the following JavaScript to modify the width property in the stylesheet:

var rule = document.styleSheets[0].cssRules[0];
rule.selectorText = "#tId";
rule.value = "width: 30%";

This will update the stylesheet rule to:

#tId {
      width: 30%;
   }

Note that inline styles still take precedence over stylesheet values. To override inline styles, use document.getElementById('id').style.width = value.

The above is the detailed content of How Can I Modify CSS Stylesheet Values 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