Home > Web Front-end > JS Tutorial > How to Extract the Entire CSS Rule Content as a String?

How to Extract the Entire CSS Rule Content as a String?

Linda Hamilton
Release: 2024-12-13 02:36:11
Original
161 people have browsed it

How to Extract the Entire CSS Rule Content as a String?

How to Extract CSS Rule Values

How can you return a string containing all the contents of a CSS rule, like the format you'd see in an inline style? This can be done without knowing the specific content of the rule, avoiding the need to extract them by style name.

Consider the following CSS:

.test {
    width:80px;
    height:50px;
    background-color:#808080;
}
Copy after login

To begin, we have the following code:

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
            //this is where I can collect the style information, but how?
        }
    }
}
getStyle('.test')
Copy after login

Building on scunliffe's answer and adapting from another source, we can enhance this code to extract the CSS rule values:

function getStyle(className) {
    var cssText = "";
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {        
        if (classes[x].selectorText == className) {
            cssText += classes[x].cssText || classes[x].style.cssText;
        }         
    }
    return cssText;
}

alert(getStyle('.test'));
Copy after login

This code traverses the CSS rules, checking if the selector text matches the specified class name. For each matching rule, it collects the corresponding CSS text and accumulates it into the cssText variable. Finally, the function returns the accumulated CSS text, providing a string with the desired inline style format.

The above is the detailed content of How to Extract the Entire CSS Rule Content as a String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template