Reputation: 438
I am looking for a way to do a for each loop over XML that is returned from an ajax request. I have the below code which logs the value of the id attribute of the first success element.
How can I change this to go over all 20,50,70 etc success elements and print the values of their id attribute?
$.ajax({
type: 'GET',
url: url,
data: {},
dataType: "xml",
success: function(xml) {
var id = $(xml).find('success').attr('id');
console.log(id);
}
});
Example XML:
<body>
<success id="1" ></success>
<success id="2" ></success>
</body>
Upvotes: 0
Views: 2071
Reputation: 24638
Change:
var id = $(xml).find('success').attr('id');
console.log(id);
To:
$(xml).find('success').each(function() {
var id = $(this).attr('id');
console.log(id);
});
Reference:
var xml = '<body>\
<success id="1" ></success>\
<success id="2" ></success>\
</body>';
xml = $.parseXML(xml);
$(xml).find('success').each(function() {
var id = $(this).attr('id');
alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1