从文档中Get Attributes的探究

从HTML DOM文档中获取DOM节点的某个Attribute的时候,我们通常都会使用getAttribute方法,或许大家都明白,getAttribute在获取for和class等属性时,浏览器的兼容性不理想,需要特殊处理,原因在于class、for是Javascript的关键字。因此需要相应的转化成className、htmlFor来获取他们的属性值比如:

element.getAttribute("class");  ===> return null;
element.getAttribute("for");  ===>return null;

使用getAttribute来获取属性的值还有其他的一些问题:比如想要获取DOM节点的事件属性或者href、src的时候都是存在问题的:

<a href="/index.html" onclick="alert('Back home!')">Home</a>
element.getAttribute('href');
// -> "http://tobielangel.com/index.html" in IE
// -> "/index.html" in well behaved browsers

element.getAttribute('onclick');
// -> "function anonymous(){alert('Back home!')}" in IE
// -> "alert('Back home!')" elsewhere.

上面的这些兼容性问题都是getAttribute所解决不了的。现在我们来看一个“亮点”:使用getAttribute的第二个参数iFrag。根据微软官方的解释,使用第二个参数设置为2的时候会返回属性直接的值,而不会自动转化。但是这又将会出现什么问题呢?

<a href="/index.html" onclick="alert('Back home!')">Home</a>
//iFrag的作用很好的解决了href的兼容性问题
element.getAttribute('href', 2);
// -> "/index.html" in IE
// -> "/index.html" in well behaved browsers

//但是:事件属性的问题依然没有解决
element.getAttribute('onclick', 2);
// -> "function anonymous(){alert('Back home!')}" in IE
// -> "alert('Back home!')" elsewhere.

还有没有其他的办法呢? 或许大家会再次想到使用attributes collection。没错,attributes可以解决了事件属性的问题,同时也可以解决class和for的问题:

element.attributes['onclick'];
// -> "alert('Back home!')"

但是attributes collection也并不兼容href,style,onload,value,input,valign等等一连串的其他的属性。所以attributes collection并不是一个好的解决问题的方法。

通过查阅Mozilla DOM API,查看到一个类似的方法:getAttributeNode。了解到它的使用方法之后,再次测试,发现它兼容class,for,和事件属性以及src等敏感属性,在各个浏览器都兼容的很好,但是它对于href属性问题依然存在,IE和其他浏览器显示的值不一样。万般无奈之际,也就只有写一个兼容的通用函数来处理了。下面是我写的一个通用函数:

function getAttributeCustom(element,attr){
	return attr === "href" ? element.getAttribute("href",2) : element.getAttributeNode(attr).value;
}

它结合了上面分析的方法来解决一些敏感属性的取值。在这个方法中,你可以直接传入class和for字符串,而不用className和htmlFor来替代。