js添加和删除class

时间:2022-09-04 21:12:08

原生主要有三种方法:

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);

@