js添加和删除class - 孤独大兔子

时间:2024-03-10 16:23:59

js添加和删除class

2019-01-30 18:15  孤独大兔子  阅读(6025)  评论(0编辑  收藏  举报

原生主要有三种方法:

1、className

var DomClass = document.getElementById("id").className;
//删除 pat
DomClass = DomClass.replace(\'pat\',"");
document.getElementById("id").className = DomClass;

//添加 pad
DomClass = DomClass.concat(\'pat\');
document.getElementById("id").className = DomClass;

//替换 pad
DomClass = DomClass.replace(\'pat\',"pad");
document.getElementById("id").className = DomClass;

2、es5的classList

var DomClass = document.getElementById("id");
//删除 pat
DomClass.classList.remove("pat");

//添加 pad
DomClass.classList.add("pat");

3、同一 setAttribute

var DomClass = document.getElementById("id").getAttribute(\'class\');
//删除 pat
DomClass = DomClass.replace(\'pat\',"");
document.getElementById("id").setAttribute(\'class\',DomClass);

//添加 pad
DomClass = DomClass.concat(\'pat\');
document.getElementById("id").setAttribute(\'class\',DomClass);

//替换 pad
DomClass = DomClass.replace(\'pat\',"pad");
document.getElementById("id").setAttribute(\'class\',DomClass);

@