假设HTML如下,一个div
<div id="a" name='123' align="bottom" bgColor='green'></div>
function getAttrList(element){
var arr = [],
attrName,
attrValue,
i,
len,
attrs = element.attributes;
for(i=0,len=attrs.length; i<len; i++){
attrName = attrs[i]['nodeName'];
attrValue = attrs[i]['nodeValue'];
if(attrs[i]['specified']){
arr.push(attrName+"=\""+attrValue+"\"");
}
}
return arr.join(' ')
}
getAttrList(document.getElementById('a')); //id="a" name="123" align="bottom" bgcolor="green"
上面的attrs[i]['specified']
是为了兼容低版本的IE,以确保每个属性都是已设置的,在低版本的IE中,所有未设置的特性的specified
属性值都为false