1.element要用getElementById or ByTagName来获得,javascript
2.setAttribute("class", vName)中class是指改变"class"这个属性,因此要带引号。css
3.IE中要把class改为className,.....IE不认class,因此最好写两句,都用上吧。java
W3C DOM - {setAttribute()}浏览器
setAttribute(string name, string value):增长一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。函数
一、关于class和className
class属性在W3C DOM中扮演着很重要的角色,但因为浏览器差别性仍然存在。使用setAttribute("class", vName)语句动态设置
Element的class属性在firefox中是行的通的,在IE中却不行。由于使用IE内核的浏览器不认识"class",要改用"className";
一样,firefox 也不认识"className"。因此经常使用的方法是两者兼备:
element.setAttribute("class", vName);
element.setAttribute("className", vName); //for IEui
二、setAttribute()的差别
咱们常常须要在JavaScript中给Element动态添加各类属性,这能够经过使用setAttribute()来实现,这就涉及到了浏览器的兼容性问题。
var bar = document.getElementById("foo");
bar.setAttribute("onclick", "javascript:alert('This is a test!');");
这里利用setAttribute指定e的onclick属性,简单,很好理解。可是IE不支持,IE并非不支持setAttribute这个函数,
而是不支持用setAttribute设置某些属性,例如对象属性、集合属性、事件属性,也就是说用setAttribute设置style和onclick这些属性
在IE中是行不通的。为达到兼容各类浏览器的效果,能够用点符号法来设置Element的对象属性、集合属性和事件属性。
程序代码
document.getElementById("foo").className = "fruit";
document.getElementById("foo").style.cssText = "color: #00f;";
document.getElementById("foo").style.color = "#00f";
document.getElementById("foo").onclick= function () { alert("This is a test!"); }firefox