javascript - How to implement jq's addclass and removeclass in js. For example, it is originally class="aa" and needs to be changed to class="aa bb"
怪我咯
怪我咯 2017-07-05 10:44:24
0
5
1119

How to implement jq's addclass and removeclass in js. For example, it is originally class="aa" and it needs to be changed to class="aa bb". Be careful not to use jquery

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(5)
曾经蜡笔没有小新

js has a classlist interface
MDN link

But you have to consider compatibility.

習慣沉默

if (!this.hasClass(obj, class)) obj.className += " " + class;

ringa_lee

elem.className
or
elem.classList
I feel classList is better, elem.classList.add('bb') will do
In addition, the jQuery source code implements addClass and removeClass through className
Finally, this bias For basic questions, you need to learn how to Baidu and Google yourself

学习ing
function addClass(ele,name){
        if(ele && name){
            var cn = ele.className;
            if(!cn){
                ele.className = name;
            }else if(cn.indexOf(name) === -1){
                ele.className = cn.replace(/\s*$/,' '+name);
            }
        }
}
function removeClass(ele,name){
        var reg1 = new RegExp('^\\s*\\b'+ name +'\\b\\s*$');
        var reg2 = new RegExp('^\\s*' + name+'\\b');
        var reg3 = new RegExp('\\b'+ name + '\\s*$');
        var reg4 = new RegExp('\\s*\\b'+name+'\\b\\s*');
        if(ele && name){
            var cn = ele.className;
            if(cn && cn.indexOf(name) > -1){
                if(reg1.test(cn)){
                    ele.className = '';
                }else if(reg2.test(cn)){
                    ele.className = cn.replace(reg2,'');
                }else if(reg3.test(cn)){
                    ele.className = cn.replace(reg3,'');
                }else{
                    ele.className = cn.replace(reg4,' ');
                }
            }
        }
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template