Home > Article > Web Front-end > How can I dynamically change CSS class rules using jQuery without touching the DOM?
To change the font size of a CSS class named ".classname" using jQuery, without adding inline CSS or directly manipulating the DOM, follow these steps:
<code class="javascript">// Get the CSS stylesheet var styleSheet = document.styleSheets[0]; // Loop through the CSS rules within the stylesheet for (var i = 0; i < styleSheet.cssRules.length; i++) { // Check if the current rule is for the ".classname" class if (styleSheet.cssRules[i].selectorText === ".classname") { // Set the new font size for the rule styleSheet.cssRules[i].style.fontSize = "16px"; } }</code>
To save the modified CSS class rules to a file, you'll need to create an Ajax POST request to the server.
<code class="javascript">// Build a string containing the updated CSS declarations var updatedCSS = ""; for (var i = 0; i < styleSheet.cssRules.length; i++) { updatedCSS += styleSheet.cssRules[i].selectorText + " {\n"; for (var j = 0; j < styleSheet.cssRules[i].style.length; j++) { updatedCSS += " " + styleSheet.cssRules[i].style[j] + ": " + styleSheet.cssRules[i].style.getPropertyValue(styleSheet.cssRules[i].style[j]) + ";\n"; } updatedCSS += "}\n"; } // Send the updated CSS to the server $.ajax({ type: "POST", url: "/save-css", data: { updatedCSS: updatedCSS } });</code>
On the server-side, create a script to save the received updated CSS to a file.
The above is the detailed content of How can I dynamically change CSS class rules using jQuery without touching the DOM?. For more information, please follow other related articles on the PHP Chinese website!