Hier ist eine Übersicht über die vielen Möglichkeiten, die sowohl für meine als auch für Ihre Referenz verwendet werden können :) Die Funktionen geben einen Hash von Attributnamen und deren Werten zurück.
Vanilla JS :
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Vanilla JS mit Array.reduce
Funktioniert für Browser, die ES 5.1 (2011) unterstützen. Benötigt IE9 +, funktioniert nicht in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
Diese Funktion erwartet ein jQuery-Objekt, kein DOM-Element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Unterstreichen
Funktioniert auch für lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Ist noch prägnanter als die Underscore-Version, funktioniert aber nur für lodash, nicht für Underscore. Benötigt IE9 +, ist in IE8 fehlerhaft. Ein großes Lob an @AlJey für diesen einen .
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Testseite
Bei JS Bin gibt es eine Live-Testseite, die alle diese Funktionen abdeckt. Der Test enthält boolesche Attribute ( hidden
) und aufgezählte Attribute ( contenteditable=""
).
$().attr()