Cross-browser, javascript getAttribute() method?

前端 未结 3 1729
無奈伤痛
無奈伤痛 2020-12-14 03:45

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

相关标签:
3条回答
  • 2020-12-14 04:24

    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.

    0 讨论(0)
  • 2020-12-14 04:35

    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.

    0 讨论(0)
  • 2020-12-14 04:41

    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.

    0 讨论(0)
提交回复
热议问题