Home >Web Front-end >JS Tutorial >How Can I Retrieve a CSS Class's Declaration as a String?
Question:
How can I obtain the complete CSS declaration of a specific class as a string?
Context:
Consider the following HTML and CSS:
<html> <head> <style> .test { width: 80px; height: 50px; background-color: #808080; } </style> </head> <body> <div class="test"></div> </body> </html>
Given this CSS, I want to return a string that displays the inline style representation of the .test class, without directly accessing individual style properties.
Answer:
To obtain the complete CSS declaration of a specific class:
function getStyle(className) { var cssText = ""; // Get all CSS rules var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules; // Iterate through rules for (var x = 0; x < classes.length; x++) { // If the class name matches the rule if (classes[x].selectorText == className) { // Capture the CSS declaration cssText += classes[x].cssText || classes[x].style.cssText; } } // Return the captured CSS declaration return cssText; } // Usage example: var result = getStyle(".test"); console.log(result); // Output: "width: 80px; height: 50px; background-color: #808080;"
The above is the detailed content of How Can I Retrieve a CSS Class's Declaration as a String?. For more information, please follow other related articles on the PHP Chinese website!