Home >Web Front-end >CSS Tutorial >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:
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'`
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!