Skip to content Skip to sidebar Skip to footer

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 f

Solution 1:

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.

Solution 2:

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.

Solution 3:

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.

Post a Comment for "Cross-browser, Javascript Getattribute() Method?"