.a{ color: red; } #id box var box = document.getElementById(‘box‘); box.setAttribute(‘class‘,‘a‘);
IE6/7 : div背景色不是红色
IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色为红色
结果:IE6/7不支持setAttribute(‘class‘,‘xxx‘)方式设置元素的class。
.a{ color: red; } #id box var box = document.getElementById(‘box‘); box.setAttribute(‘className‘,‘a‘);
IE6/7 : div背景色为红色
IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色不是红色
结果:IE8/9/10/Firefox/Safari/Chrome/Opera不支持setAttribute(‘className‘,‘xxx‘)方式设置元素的class。
.a{ color: red; } .b{ font-size: 18px; } #id box var box = document.getElementById(‘box‘); box.className = ‘a‘; box.className += ‘ b‘; //前加空格
结果:所有浏览器都支持。
.a{ color: red; } .b{ font-size: 18px; } .c{ background: #8A2BE2; } #id box var box = document.getElementById(‘box‘); //console.log(box.classList); box.classList.add(‘a‘); //添加 box.classList.remove(‘b‘); //删除 box.classList.toggle(‘c‘) //如果有相应的class就删除,没有就添加 var if_b = box.classList.contains(‘a‘); //查找有没有相应的 class,返回true/false console.log(if_b);
JavaScript中设置元素class,添加/删除元素class的方法
原文:https://www.cnblogs.com/suitongyu/p/12071887.html