Get all Attributes from a HTML element with Javascript/jQuery
If you just want the DOM attributes, it's probably simpler to use the attributes
node list on the element itself:
var el = document.getElementById("someId");
for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){
arr.push(atts[i].nodeName);
}
Note that this fills the array only with attribute names. If you need the attribute value, you can use the nodeValue
property:
var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
att = atts[i];
nodes.push(att.nodeName);
values.push(att.nodeValue);
}
You can use this simple plugin as $('#some_id').getAttributes();
(function($) {
$.fn.getAttributes = function() {
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( index, attr ) {
attributes[ attr.name ] = attr.value;
} );
}
return attributes;
};
})(jQuery);
Simple:
var element = $("span[name='test']");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
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();
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();