js添加和刪除class


原生主要有三種方法:

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

@


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM