js中设置元素class的三种方法小结

 一、el.setAttribute('class','abc');
代码如下:

 .abc {
    background: red;
  }
test div
 var div = document.getElementById('d1');
 div.setAttribute("class", "abc");
    IE6/7 : div背景色不是红色
    IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色为红色
    结果:IE6/7不支持setAttribute('class',xxx)方式设置元素的class。
 二、el.setAttribute('className', 'abc')
   
代码如下:
 
  .abc {
    background: red;
    }
test div

    var div = document.getElementById('d1');
    div.setAttribute("className", "abc");

    IE6/7 : div背景色为红色
    IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色不是红色
    结果:IE8/9/10/Firefox/Safari/Chrome/Opera不支持setAttribute('className',xxx)方式设置元素的class。
    很有趣,使用setAttribute的时候第一个参数为class和className的情形在IE6/7和IE8/9/10/Firefox/Safari/Chrome/Opera刚好相反。
三、el.className = 'abc';
  代码如下:
 .abc {
  background: red;
  }
test div
   var div = document.getElementById('d1');
   div.className = 'abc';
    所有浏览器都支持。

原文地址:http://www.shangxueba.com/jingyan/1906397.html




原文地址:https://www.cnblogs.com/liuyandeng/p/5824023.html