Oto przegląd wielu sposobów, które można zrobić, zarówno dla siebie, jak i dla Ciebie :) Funkcje zwracają skrót nazw atrybutów i ich wartości.
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 z Array.reduce
Działa dla przeglądarek obsługujących ES 5.1 (2011). Wymaga IE9 +, nie działa w 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
Ta funkcja oczekuje obiektu jQuery, a nie elementu DOM.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Podkreślać
Działa również na lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Jest jeszcze bardziej zwięzły niż wersja Underscore, ale działa tylko dla lodash, a nie dla Underscore. Wymaga IE9 +, zawiera błędy w IE8. Uznanie dla @AlJey za to .
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Strona testowa
W JS Bin istnieje strona testowa na żywo obejmująca wszystkie te funkcje. Test zawiera atrybuty boolowskie ( hidden
) i atrybuty wyliczeniowe ( contenteditable=""
).
$().attr()