I know individual attributes can be retrieved with the attr() method, but I\'m trying to iterate over all of the attributes for an element. Fo
I am posting here because I think it may help others that arrive at this posting looking to parse an xml file as I was.
I was looking for a method of traversing an xml file with a very similar structure to theracoonbear's fle and storing the results in an array and came across this posting.
I looked at prodigitalson's code but I simply could not get this syntax to work - with firefox complaining that in the line:
$.each(this.attributes, function(i, attrib){
that
this.attributes
is not a defined function. I am quite sure that the error is entirely mine. But I have spent several hours attempting to get this working and have failed
What worked for me was (where my tag name is session instead of item):-
$(xml_Data).find("session").each(function() {
console.log("found session");
$(this).children().each(function(){
console.log("found child " + this.tagName);
console.log("attributes" + $(this).text());
});
});
I appreciate that this may not exactly answer the original question. However I hope that it may save other visitors to this post some time.
Regards
While you can just use the standard DOM Element attribute attributes, it will include every attribute (even those not explicitly set) in IE6. As an alternative, you can limit the number of attributes you set:
var use_attributes = ['id','name','value','type'];
$(xml).find('item').each(function() {
var $item = $(this);
$.each( use_attributes, function(){
if($item.attr( this )){
// Act on the attribute here.
// `this` = attribute name
// $item.attr( this ) = attribute value
}
})
});