trying to determine a decent, cross browser method for obtaining attributes with javascript? assume javascript library use (jQuery/Mootools/etc.) is not an option.
I’ve tried the following, but I frequently get “attributes” is null or not an object error when IE tries to use the “else” method. Can anyone assist?
<script type="text/javascript">
//...
getAttr: function(ele, attr) {
if (typeof ele.attributes[attr] == 'undefined'){
return ele.getAttribute(attr);
} else {
return ele.attributes[attr].nodeValue;
}
},
//...
</script>
<div>
<a href="http://www.yo.com#foo">Link</a>
</div>
using the above html, in each browser, how do I getAttr(ele, ‘href’)? (assume selecting the ele node isn’t an issue)
With regard to your question’s update, you could try this.
It may be overkill, but if
getAttribute()and the dot notation don’t return a result, it iterates through theattributesobject to try to find a match.Example: http://jsfiddle.net/4ZwNs/
It’s up to you to do some cross-browser testing, though. :o)
Using
ele.attributes, you need to access them by index, as in:Trying to pass
attributesan attribute name appears to return a value whosetypeofisobject, so yourelsecode is running even thoughele.attributes[attr]doesn’t give you the value you want.