tester
tester

Reputation: 23159

Cross-browser, javascript getAttribute() method?

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)

Upvotes: 15

Views: 29661

Answers (3)

Mark Rhodes
Mark Rhodes

Reputation: 10217

For the vast majority of cases you can simply use the built in getAttribute function.

e.g.

ele.getAttribute(attr)

According to QuirksMode this should work on all major browsers (IE >= 6 included), with a minor exception:

In IE5-7, accessing the style attribute gives an object, and accessing the onclick attribute gives an anonymous function wrapped around the actual content.

Upvotes: 16

user113716
user113716

Reputation: 322492

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.

Upvotes: 10

Robusto
Robusto

Reputation: 31883

You are trying to access properties of ele before you've established if those properties exist. Try this kind of evidence chain:

if (ele.attributes && ele.attributes[attr] && typeof ele.attributes[attr] == 'undefined')

etc.

Upvotes: 5

Related Questions