Modifying Global CSS Values Using JavaScript
Problem Overview
When manipulating the CSS styles of elements with JavaScript, it is possible to inadvertently change inline style values, overriding global CSS declarations. This can lead to inconsistent behavior and incorrect results.
Solution
To modify global CSS values, use the document.styleSheets API. This API provides access to the StyleSheetList, which contains all the CSS stylesheets in the document. By iterating through this list, you can identify the desired stylesheet and modify its rules.
Implementation
To manipulate global CSS values given an element ID, follow these steps:
Example Code
The following code demonstrates how to change the background color of an element with the ID "container":
<code class="javascript">// Get the element const element = document.getElementById('container'); // Iterate through stylesheets for (let i = 0; i < element.styleSheets.length; i++) { // Access the CSS rules const cssRules = element.styleSheets[i].cssRules; // Find the rule matching the element's ID for (let j = 0; j < cssRules.length; j++) { if (cssRules[j].selectorText === '#container') { // Change the background color cssRules[j].style.backgroundColor = 'red'; break; } } }</code>
The above is the detailed content of How to Modify Global CSS Values Using JavaScript: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!