我需要根据随机属性值找到随机节点。为此,我使用getElementsByTagName获取的节点上的getAttribute。
似乎当我将类名作为属性查找时,在IE上不起作用(在FF上可以)。
有人知道getAttribute是否仅适用于'class',还是其他属性也不适用?(如果只是类,我会想出解决方法。)
我需要根据随机属性值找到随机节点。为此,我使用getElementsByTagName获取的节点上的getAttribute。
似乎当我将类名作为属性查找时,在IE上不起作用(在FF上可以)。
有人知道getAttribute是否仅适用于'class',还是其他属性也不适用?(如果只是类,我会想出解决方法。)
如果您没有使用类似于jQuery这样的工具来简化操作,那么测试所有JavaScript跨平台是值得的,但Class可能只是一个特殊情况。
以下代码应该是一种跨平台获取class的方法:
element.className
disabled, readOnly, checked, selected, multiple,
compact, declare, isMap, noHref, defer, noResize,
size, cols, rows, width, height, hspace, vspace,
maxLength, tabIndex, colSpan, rowSpan
以及可能我错过的其他人!
element.getAttribute(x)
在IE中,确切地说等同于以下内容:
element[x]
一般而言,应该避免使用getAttribute方法,而是使用简单的DOM Level 1/2 HTML接口,例如'element.className'。
这个问题在IE8中得到了修复。
IE在这方面存在问题。你可以通过getAttribute("className")
来访问IE中的class,但是这并不是真正的属性,所以在非IE中无法使用。
这就让你面临一个选择:要么分支获取element.className,要么分支获取"className"或"class"的getAttribute。这并不好。
var value = "";
var elements = document.getElementsByTagName("div");
for(var i = 0; i < elements.length; i++){
if(typeof elements[i].attributes['class'] == "undefined"){
value = elements[i].getAttribute("class");
} else {
value = elements[i].attributes['class'].nodeValue;
}
alert(value); // careful, this will be a lot of alerts
}
在这里,您可以使用跨浏览器兼容性获取和设置类属性。
//also works with IE7 and below
//get class attribute value
var class_name = document.getElementById('elem_id').className;
//set class attribute
document.getElementById('elem_id').className = 'new-class-name';