Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import CSS just for some classes or ids?

Say, I have this HTML structure:

<div id="header">Header</div>
<div id="body">Body</div>
<div id="footer">Footer</div>

And an external CSS file (/styles.css), which contains

#header{
    color:red;
}    
#footer{
    color:red;
}

Now with the help of javascript I can easily load the whole CSS, so as the text color of #header and #footer becomes red.

Using javascript, is it possible to load only styles which refer to #header and filter out any other styles in my stylesheet (styles for #footer in my case)?

like image 934
nicael Avatar asked Feb 03 '26 20:02

nicael


1 Answers

This can be done by directly modifying the CSS rules being applied to the current document.

<script type="text/javascript">
    // Important: Place this where it will be executed once all the CSS resources have been loaded (i.e, beginning or the end of the body tag)

    // The will be an array of all the selectors to keep CSS rules for
    ruleList = ["#header"];
    var docRulesEntry = document.all ? 'rules' : 'cssRules';

    // Loop through loaded stylesheets
    for(var i = 0; i < document.styleSheets.length; i++)
    {
        if(document.styleSheets[i][docRulesEntry] !== null && document.styleSheets[i][docRulesEntry] !== undefined)
        {
            // Loop through stylesheet rules
            for(var o = 0; o < document.styleSheets[i][docRulesEntry].length; o++)
            {
                if(document.styleSheets[i][docRulesEntry][o] !== null && document.styleSheets[i][docRulesEntry][o] !== undefined)
                {
                    // Check if selector exists in our ruleList array
                    if(ruleList.indexOf(document.styleSheets[i][docRulesEntry][o].selectorText) == -1
                        && document.styleSheets[i][docRulesEntry][o].style !== undefined && document.styleSheets[i][docRulesEntry][o].style !== null)
                    {
                        // Selector was not found, remove CSS rules
                        document.styleSheets[i][docRulesEntry][o].style.cssText = '';
                    }
                }
            }
        }
    }
</script>

JSFiddle demo (tested on Chrome): https://jsfiddle.net/ud5svdky/1/

like image 152
Bryan Way Avatar answered Feb 06 '26 10:02

Bryan Way



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!