简体   繁体   中英

How to get CSS class by name from StyleSheet?

I have the following code which uses the index to get stylesheet and also css class inside that stylesheet.

 for (var s = document.styleSheets.length - 1; s >= 0; s--) {
            if (document.styleSheets[s].href && (document.styleSheets[s].href.indexOf("MySheet.css")!=-1)) {
                     var cssRules = document.styleSheets[s].cssRules ||
                             document.styleSheets[s].rules || []; // IE support
                     for (var c = 0; c < cssRules.length; c++) {
                         if (cssRules[c].selectorText === ".myclass ")
                             cssRules[c].style.backgroundColor = 'powderblue';
                     }
             }
       }

Though I get CSS class by its name in the above code I need to avoid this looping.Is it possible to get CSS class by querying it??How to do this??else some other way to avoid this looping??

Here's a snippet you can use to create new rules and manipulate existing rules in a stylesheet. A particular sheet is recognized by its title , so you need to give unique titles to those stylesheets you want to manipulate (add title attribute to corresponding link or style tags).

function CssManipulator (sheetTitle) {
    var that = this,                        // A reference to an instance
        len = document.styleSheets.length,  // Caches the length of the collection
        n;                                  // General loop counter
    this.styleSheet = null;                 // Stores the stylesheet for the instance
    this.selectors = {};                    // Stores the selectors we've handled
    this.cssRules = null;                   // Caches cssRules of the given stylesheet
    // Search the given stylesheet by title and assign it and its cssRules to instance properties
    for (n = 0; n < len; n++) { 
        if (document.styleSheets[n].title === sheetTitle) {
            this.styleSheet = document.styleSheets[n];
            this.cssRules = document.styleSheets[n].cssRules || document.styleSheets[n].rules;
            break;
        }
    }
    // Changes properties of the given selector
    this.change = function (selector, prop, value) {
        // FF knows only camel-cased propertynames, hence camel-casing the propName
        var propName = (prop.charAt(0) === '-') ? prop.substring(1, prop.length) : prop;        
        propName = propName.replace(/-([a-z])/gi, function(str, chr) {
            return chr.toUpperCase();
        }); 
        if (selector in that.selectors) { // Change the rule, if we've handled this selector before
            that.styleSheet.cssRules[that.selectors[selector]].style[propName] = value;
        } else { // Add a new rule if we haven't met this selector before
            that.selectors[selector] = that.styleSheet.insertRule(selector + '{' + prop + ':' + value + ';}', that.cssRules.length);
        }
    };
}

selectors contains the magic, it stores the index of the newly-created rule returned by insertRule .

Usage

Create an instance of CssManipulator for every stylesheet you want to change like this:

pageSheet = new CssManipulator('title_of_the_stylesheet');

Then you can manipulate most of the rules in a stylesheet (pseudo-elements can't be manipulated with this code) by calling object's change method:

pageSheet.change('.some_selector', 'property-name', 'value_for_the_property');

This method adds a new selector once, nevertheless if the passed selector exists in the original stylesheet or not. Notice, that if you change a property name like background-color , you need to pass "hyphen-mode" of the property name to the method.

You can develope the object further, for example change method could be easily changed to accept more than one property-value pair per call.

If I understands correctly, you want to change CSS. Precisely you want to change CSS rules for a class. To do so, and to be the most performance efficient, I would create a stylesheet with your selectors, it might be just .selector>div{} for example or just .selector{} .

<style type="text/css">.squerify>tr{height:60px;}</style>

I used this a while ago to make my table cells square (while my cells was all equal).

Then I used this code to change parameters of the class in the stylesheet.

document.styleSheets[0].cssRules[numberOfSelector].style.height=document.querySelector('.squerify td').offsetWidht+"px";

This was the best way I could think of, but if you want, you could use a loop to search for the classes.
Send a comment if misunderstood your question.

var someVar = document.querySelectorAll('.someClass');
for(var i=0; i<someVar.length; i++){
someVar[i].style.background = 'powderBlue';}

This will grab all of the elements with the class 'someClass' and change the background color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM