一、classList的add()和remove()方法
css样式
.new{ color: #FFD113; }
html标签
<span class="old">首页</span>
js代码
var arr = document.getElementsByTagName("span"); arr[i].classList.add("new"); /*添加样式*/ arr[j].classList.remove("new");/*删除样式*/
二、字符串拼接 className
var old= element.className; /*加上空格, 不然想查询"old",若原本有"older"的类名的就会有问题*/ old = " " + old + " "; /*查询类名中是否含有某个class*/ old.indexOf(" ClassName ") === -1 ? false : true;//同样的查询时也要带上空格*2 /*增加*/ 1. new=old+" new";//注意空格*1 2. new = old.concat(" ClassName");//注意空格*1 element.setAttribute("class", new); /*删除*/ new = old.replace(" ClassName "," ");//注意空格*3 element.setAttribute("class",new); /*修改*/ new = old.replace(" targetClassName "," yourClassName ");//注意空格*4 element.setAttribute("class",new );