-2

I have the following code:

$.ajax({
    url: (path+args),
    type: "POST",
    success: function( data ){
        // do stuff with "data"
    }
});

If data looks like the following:

<div id="imageList">
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
    <div class="image"></div>
</div>

How can I iterate through data which has the divs?

Howard
  • 3,648
  • 13
  • 58
  • 86

3 Answers3

3

If you have control of what the server is returning, I'd probably send JSON back to the browser – something like:

[
    { url: "a.png" },
    { url: "b.png" }
]

...which makes it easy to do something like for (var i = 0; i < data.length; i++) data[i].url.

That said, if you don't have control over what's coming back from the server, you can create a fragment with the returned data and use normal jQuery methods.

$(data).children('.image').each(function() {
    var url = $(this).children('img').attr('src');  // or whatever
});

This works because passing a string of HTML to jQuery creates a DocumentFragment, parsing the HTML in your string and creating a "mini-DOM". The returned jQuery object selects the top-level element of that DOM (in this case, div#imageList), and you can traverse the fragment DOM freely.

In my example, I select the children of #imageList with class image and then iterate over each selected element.

josh3736
  • 139,160
  • 33
  • 216
  • 263
  • Is the json method faster? – Howard Oct 21 '13 at 03:53
  • Absolutely. Rule number one of working with the DOM: [The DOM is *very* slow.](http://stackoverflow.com/a/11925491/201952) Browsers have native JSON parsers (`JSON.parse()`), and pure JS `for` loops over arrays are very fast. – josh3736 Oct 21 '13 at 03:55
1

you can do something like this

$(data).children('div').each(function(){
$(this).doSomething();
})
aayush shrestha
  • 1,858
  • 2
  • 17
  • 33
0

Maybe something like this:

$.each( $('#imageList'), function(i, imageList) {
   $('div', imageList).each(function() {

   });
})

or could use something like:

$("#imageList").children().each()
Kustom
  • 181
  • 3
  • 15