Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  118] [ 3]  / answers: 1 / hits: 29461  / 14 Years ago, mon, september 20, 2010, 12:00:00

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)


More From » javascript

 Answers
93

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 the attributes object to try to find a match.



Example: http://jsfiddle.net/4ZwNs/



var funcs = {
getAttr: function(ele, attr) {
var result = (ele.getAttribute && ele.getAttribute(attr)) || null;
if( !result ) {
var attrs = ele.attributes;
var length = attrs.length;
for(var i = 0; i < length; i++)
if(attrs[i].nodeName === attr)
result = attrs[i].nodeValue;
}
return result;
}
};

var result = funcs.getAttr(el, 'hash');


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:



ele.attributes[0].nodeName;   // id (for example)
ele.attributes[0].nodeValue; // my_id (for example)


Trying to pass attributes an attribute name appears to return a value whose typeof is object, so your else code is running even though ele.attributes[attr] doesn't give you the value you want.


[#95560] Friday, September 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aliah

Total Points: 118
Total Questions: 132
Total Answers: 94

Location: Tajikistan
Member since Fri, Sep 11, 2020
4 Years ago
;