How do I add a class to a given element?

前端 未结 25 2359
清酒与你
清酒与你 2020-11-21 11:34

I have an element that already has a class:

25条回答
  •  隐瞒了意图╮
    2020-11-21 12:14

    When the work I'm doing doesn't warrant using a library, I use these two functions:

    function addClass( classname, element ) {
        var cn = element.className;
        //test for existance
        if( cn.indexOf( classname ) != -1 ) {
            return;
        }
        //add a space if the element already has class
        if( cn != '' ) {
            classname = ' '+classname;
        }
        element.className = cn+classname;
    }
    
    function removeClass( classname, element ) {
        var cn = element.className;
        var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
        cn = cn.replace( rxp, '' );
        element.className = cn;
    }
    

提交回复
热议问题