[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 version="1.0" encoding="UTF-8" standalone="yes"?>
	<image src="001.jpg" />
	<image src="003.jpg" />
	<image src="004.jpg" />
	<image src="002.jpg" />
	<image src="005.jpg" />
	<image src="006.jpg" />


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

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");

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");

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: