JavaScript access CSS class by its name?

后端 未结 6 1830
难免孤独
难免孤独 2021-01-12 16:33

I have to access CSS class by name, and the code below works. However if I try hui[\"myclass\"] or hui[\".myclass\"] instead of hui[0]

6条回答
  •  臣服心动
    2021-01-12 16:39

    To change the established rules, this is one approach:

    // the [2] index is only because that's where JS Fiddle
    // puts the user-entered CSS (from the CSS panel).
    var sheets = document.styleSheets[2].rules,
        classString = 'body',
        props = ['color'], // requires a 1:1 relationship between two arrays...ugh
        to = ['#0f0'];
    
    for (var i = 0, len = sheets.length; i < len; i++) {
        if (sheets[i].selectorText == classString) {
            for (var c = 0, leng = props.length; c < leng; c++) {
                sheets[i].style[props[c]] = to[c];
            }
        }
    }​
    

    JS Fiddle demo.

    And a slightly improved alternative (an object rather than two arrays, that require a 1:1 relationship):

    var sheets = document.styleSheets[2].rules,
        classString = 'body',
        propsTo = {
            'color': '#0f0'
        };
    
    for (var i = 0, len = sheets.length; i < len; i++) {
        if (sheets[i].selectorText == classString) {
            for (var prop in propsTo) {
                if (propsTo.hasOwnProperty(prop)) {
                    sheets[i].style[prop] = propsTo[prop];
                }
            }
        }
    }​
    

    JS Fiddle demo.

提交回复
热议问题