Getting all element attribute values with jQuery

Here is a little snippet which I have found extremely useful especially when working with XML in Javascript. You can use the following to loop through all of an element’s attributes and store them in an object:

1
2
3
4
5
6
var element = $("#myElement"),
    attributes = {};

$.each(element.get(0).attributes, function(i, attrib){
    attributes[attrib.name] = attrib.value;
});

So for example if we have the following XML node:

1
<item id="item1" name="the first item" image="thumbnail1.png" />

After running the snippet above on the node we can now access the values on the attributes object we created like so:

1
2
3
console.log( attributes.id ) // item1
console.log( attributes.name ) // the first item
console.log( attributes.image ) // thumbnail1.png

I have found this very useful when I don’t want to hard code XML parsing and I don’t need to know all the values right away.

I hope this is useful for someone else!

Posted toJavascript jQuery