Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 2044
时光说笑
时光说笑 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:35

    Setter and Getter!

    (function($) {
        // Attrs
        $.fn.attrs = function(attrs) {
            var t = $(this);
            if (attrs) {
                // Set attributes
                t.each(function(i, e) {
                    var j = $(e);
                    for (var attr in attrs) {
                        j.attr(attr, attrs[attr]);
                    }
                });
                return t;
            } else {
                // Get attributes
                var a = {},
                    r = t.get(0);
                if (r) {
                    r = r.attributes;
                    for (var i in r) {
                        var p = r[i];
                        if (typeof p.nodeValue !== 'undefined') a[p.nodeName] = p.nodeValue;
                    }
                }
                return a;
            }
        };
    })(jQuery);
    

    Use:

    // Setter
    $('#element').attrs({
        'name' : 'newName',
        'id' : 'newId',
        'readonly': true
    });
    
    // Getter
    var attrs = $('#element').attrs();
    

提交回复
热议问题