JavaScript access CSS class by its name?

后端 未结 6 1831
难免孤独
难免孤独 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 17:00

    No, you can't access them by the selector - it's a simple list. You first had to build an index for it:

    // assuming those are the right rules (ie from the right stylesheet)
    var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    
    var styleBySelector = {};
    for (var i=0; i

    Of course this is not a fool-proof method, there could be

    • multiple selectors like .myClass, .myOtherClass
    • multiple occurences of one selector (though it doesn't matter, the last declaration overwrites previous styles anyway)

    and instead of blindly assigning the color property you first should check for existence of the declaration.

提交回复
热议问题