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!
Leave a Reply
You must be logged in to post a comment.