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:
Modifying CSS Stylesheet Values
Once the desired rule is identified, you can modify it:
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!