Home >Web Front-end >JS Tutorial >Can JavaScript Dynamically Modify CSS Rule-Sets?
Question:
Can CSS rule-sets be dynamically modified using JavaScript, such as changing the styling of multiple elements with the same class on a web page?
Answer:
While it is possible to make such CSS changes with JavaScript, the process involves some complexities. A comprehensive guide for this can be found in the article "Totally Pwn CSS with Javascript."
To implement the aforementioned modification, follow these steps:
Implementation:
Firefox and IE: The code below has been tested to function in these browsers:
// Access the rule-set var styleSheet = document.styleSheets[0]; // assuming there's only one var ruleSet = styleSheet.cssRules[0]; // assuming there's only one // Modify the rule-set ruleSet.style.color = "red"; // Reapply the updated rule-set stylesheet.insertRule(ruleSet.cssText, 0);
Chrome: With updates in Chrome, support for the aforementioned DOM methods is now available.
The above is the detailed content of Can JavaScript Dynamically Modify CSS Rule-Sets?. For more information, please follow other related articles on the PHP Chinese website!