JavaScript添加和删除class类名 3种方法

今天项目有一个小要求,需要用原生JS实现,我相信很多人都会经常遇到这种情况。具体要求如下:

 

原生JS实现:为某个 <div> 元素添加 class 类名或 移除 class 类名。

document.getElementById("fujieace").classList.add("is-invalid");

 

第1种方法

添加:

document.getElementById("id").classList.add("类名");

 

删除:

document.getElementById("id").classList.remove("类名");

 

第2种方法

添加:

var classVal=document.getElementById("id").getAttribute("class");
document.getElementById("id").setAttribute("class",classVal.concat(" 类名"));

 

删除:

var classVal=document.getElementById("id").getAttribute("class");
document.getElementById("id").getAttribute("class").replace("类名"," ");

 

第三种方法

添加/删除:

document.getElementById("id").className+=" 类名";
    A+
发布日期:2021年01月02日 10:42:56  所属分类:JavaScript
最后更新时间:2021-01-02 11:57:28
付杰
  • ¥ 89.0元
  • 市场价:129.0元
  • ¥ 159.0元
  • 市场价:398.0元
  • ¥ 49.0元
  • 市场价:199.0元
  • ¥ 98.0元
  • 市场价:198.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: