[jQuery] Iterating over an XML object and appending to array

I’m just starting to pick up on jQuery and I’m a bit stuck.

What I am trying to do is take the following XML response and obtain the src attribute from each image. I then want to append that value to an array.

XML


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
	<image src="001.jpg" />
	<image src="003.jpg" />
	<image src="004.jpg" />
	<image src="002.jpg" />
	<image src="005.jpg" />
	<image src="006.jpg" />
</response>

jQuery


	<script type="text/javascript">
		// jQuery Test Statement
		//$(document).ready(function()
		//{
			//alert("jQuery 1.3.2 Enabled");
		//});
		var imageList = [];
		var i = 0;
		$(document).ready(function(){
			// Get data, parse it into an array, and pass array to imageSlideShow.
			$.ajax({
				url: 'xmlResponse.xml',
				type: 'GET',
				dataType: 'xml',
				success: function(returnedXMLResponse){
					console.log(returnedXMLResponse);
					$('response', returnedXMLResponse).each(function(){
						var tmpImageSrc = $(this).find("image").attr("src");
						console.log(tmpImageSrc);
						imageList.push(tmpImageSrc);
						alert(i);
						i++;
					})
				}  // End Success
			}); // End AJAX
			//console.log(imageList);
		});
</script>

Now my issue is when it gets to

$('response', returnedXMLResponse).each(function(){ ... }

it only iterates to the first row in the XML document and gives me 001.jpg when I output tmpImageSrc to console. It won’t cycle through the rest of the image tags as the alert only appears once with a value of 0. What am I missing? Am I not using the proper .each?

$('response', returnedXMLResponse).each(function(){ ... }

You are running your .each statement on the XMLResponse. Since there’s only one of those, you only get one result.

Think you need something like:

$(returnedXMLResponse).find("image").each(function() {
var tmpImageSrc=$(this).attr("src");
imageList.push(tmpImageSrc);
});

Thanks for the reply. While your solution didn’t seem to work, it did lead me to one that did. I modified my code to the following and it works great.


$('image', returnedXMLResponse).each(function(){
	var tmpImageSrc = $(this).attr("src");
	aImageList.push(tmpImageSrc);
})

Turns out it was because I was grabbing just the response, and there was only one response, that it wouldn’t cycle down through the images. So I changed it to image and it found all 6 images from the XML Response. Thanks for the help! :cool: