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:

[cc lang=”javascript”]
var element = $(“#myElement”),
attributes = {};

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

So for example if we have the following XML node:

[cc lang=”xml”]

[/cc]

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

[cc lang=”javascript”]

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

[/cc]

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!


Comments

5 responses to “Getting all element attribute values with jQuery”

  1. […] Here is a little snippet which I have found extremely useful especially when working with XML in Javascript.  […]

  2. netsi1964 Avatar
    netsi1964

    Thanks, it is useful for me 🙂

  3. Md.Ibrahim Avatar
    Md.Ibrahim

    Thanks for this tip!

  4. Predawi Avatar
    Predawi

    Thanks, very useful !

  5. 陳官均 Avatar
    陳官均

    very useful!

Leave a Reply