Home > Web Front-end > CSS Tutorial > How Can I Programmatically Access and Change Non-Inline CSS Values Using JavaScript?

How Can I Programmatically Access and Change Non-Inline CSS Values Using JavaScript?

Barbara Streisand
Release: 2024-12-22 22:59:18
Original
746 people have browsed it

How Can I Programmatically Access and Change Non-Inline CSS Values Using JavaScript?

Changing CSS Values with Javascript

Accessing Non-Inline CSS Values

In JavaScript, inline CSS values can be easily modified using document.getElementById('id').style.width = value. However, this method is problematic when dealing with non-inline CSS values that are defined in stylesheets. Retrieving such values using JavaScript returns Null, making it difficult to perform certain logical operations.

Programmatically Modifying Style Properties

To address this issue, CSS stylesheets can be accessed and modified programmatically. Here's how:

  1. Retrieve the array of stylesheets using document.styleSheets.
  2. Locate the specific stylesheet by comparing its document.styleSheets[styleIndex].href property to the expected path.
  3. Get the array of CSS rules using document.styleSheets[styleIndex].rules in IE or document.styleSheets[styleIndex].cssRules in other browsers.
  4. Identify the desired rule by comparing its selectorText property to the known selector (e.g., #tId).

Once the rule is identified, its value property can be read and set. This allows for both retrieval and modification of CSS values without changing inline styles. The following code demonstrates this process:

var styleIndex = 0; // Index of the stylesheet to modify
var ruleIndex = 1; // Index of the rule to modify
var cssRuleCode = document.all ? 'rules' : 'cssRules'; // Account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText; // e.g., '#tId'
var value = rule.value; // Get the current value or set a new value using `rule.value = 'new_value'`
Copy after login

The above is the detailed content of How Can I Programmatically Access and Change Non-Inline CSS Values Using 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