Home  >  Article  >  Web Front-end  >  js中设置元素class的三种方法小结_javascript技巧

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

WBOY
WBOYOriginal
2016-05-16 18:02:591201browse
一、el.setAttribute('class','abc');
复制代码 代码如下:





setAttribute('class', 'abc')



test div

<script> <BR>var div = document.getElementById('d1'); <BR>div.setAttribute("class", "abc"); <BR></script>



IE6/7 : div背景色不是红色
IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色为红色
结果:IE6/7不支持setAttribute('class',xxx)方式设置元素的class。
二、el.setAttribute('className', 'abc')
复制代码 代码如下:





setAttribute('className', 'abc')



test div

<script> <BR>var div = document.getElementById('d1'); <BR>div.setAttribute("className", "abc"); <BR></script>



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';
复制代码 代码如下:





el.className = 'abc'



test div

<script> <BR>var div = document.getElementById('d1'); <BR>div.className = 'abc'; <BR></script>



所有浏览器都支持。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn