Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 2045
时光说笑
时光说笑 2020-11-22 05:07

I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:



        
17条回答
  •  借酒劲吻你
    2020-11-22 05:45

    Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:

    (function($) {
        $.fn.getAttributes = function () {
            var elem = this, 
                attr = {};
    
            if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) { 
                n = n.nodeName||n.name;
                v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
                if(v != undefined && v !== false) attr[n] = v
            })
    
            return attr
        }
    })(jQuery);
    

    Usage:

    var attribs = $('#some_id').getAttributes();
    

提交回复
热议问题