theraccoonbear theraccoonbear - 3 months ago 5x
jQuery Question

Iterating over element attributes with jQuery

I know individual attributes can be retrieved with the

method, but I'm trying to iterate over all of the attributes for an element. For context, I'm using jQuery on some XML...

<item id="id123" name="Fizz" value="Buzz" type="xyz">
<subitem name="foo">
<subitem name="bar">
<item id="id456" name="Bizz" value="Bazz" type="abc">
<subitem name="meh">
<subitem name="hem">

I am already able to iterate over the items with...

$(xml).find('item').each(function() {
// Do something to each item here...

But I'd like to be able to get an array of attributes for each 'item' so I can then iterate over those...


$(xml).find('item').each(function() {
var attributes = $(this).attributes(); // returns an array of attributes?
for (attribute in attributes) {
// Do something with each attribute...

I've done some searching here, in the jQuery documentation, and elsewhere via Google but have had no luck. If nothing else, I may just be having trouble excluding results relating to the
method of the jQuery object. Thanks in advance.


The best way is to use the node object directly by using its attributes property. The only difference in my solution below compared to others suggesting this method is that i would use .each again instead of a traditional js loop:

$(xml).find('item').each(function() {
  $.each(this.attributes, function(i, attrib){
     var name =;
     var value = attrib.value;
     // do your magic :-)