Iterating over element attributes with jQuery Iterating over element attributes with jQuery xml xml

Iterating over element attributes with jQuery


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 = attrib.name;     var value = attrib.value;     // do your magic :-)  });});


it seems you have to use plain old vanilla javascript:

for (var i = 0; i < elem.attributes.length; i++) {    var attrib = elem.attributes[i];    if (attrib.specified == true) {        console.log(attrib.name + " = " + attrib.value);    }}

How to iterate through all attributes in an HTML element?


Could you get the DOM element from the jQuery wrapper using the get() function, and then iterate the DOM attributes?

var node = $(myStuff).get(0);if (node.attributes.length) {    for (var length = attrs.length, i = 0; i < length; i++) {        if (attrs[i].specified) {        }    }}

For some much more robust DOM attribute handling, check this blog post.