JavaScript access CSS class by its name?

后端 未结 6 1862
难免孤独
难免孤独 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:54

    document.getElementsByClassName('myclass');
    

    will return an array of elements which match.

    You could also use something along the lines of:

    
        
    Some Text
    div two

    Javascript:

    var changeTheseDivs = document.getElementById('changethese');
    changeTheseDivs.getElementsByClassName('myclass')
    

    To change only the class within the selected div.

    However, support for this method only works back to IE9, so if JQuery is an option, it might be best to use that.

    Edit:

    I believe I misread, it looks like you want to change the actual CSS rule itself as opposed to changing CSS on the elements. You could, in theory, write a function that will find rules by name for you and change their properties. I guess it would look something like this (untested, should work):

    function findAndChangeCSSRule(ruleName, newRule, newProperty){
        var mysheet=document.styleSheets[0];
        var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules
        for (i=0; i

    then call it with:

    findAndChangeCSSRule('my_class', 'color', 'red')    
    

提交回复
热议问题