Raji
Raji

Reputation: 845

Get all child div values in jquery AJAX response

I need to get all child div values from the AJAX response which contains the following format.

var jqxhr = $.post('<%= url_for :action => :friend_list %>', { id: fid }, 
    function(data){
        var stripped_data = $(data).html().trim();
        var top_name = $(stripped_data).find('div.toppings_name').html();  
    }); 

In the alert of stripped_data contains the following format.

<div id="toppings>
  <div class="toppings_name">a</div>
  <div class="toppings_name">b</div>
  <div class="toppings_name">c</div>
</div> 

I tried using .find() method but getting the first child value only. How to get all the values from the parent div.

Upvotes: 1

Views: 4525

Answers (2)

JaredPar
JaredPar

Reputation: 754545

The problem is you're using html which is meant for use on a single element but actually using it on a collection. Instead you want the html contents of the outer div. Try this instead

var top_name = $(stripped_data).find('#toppings').html();

If you are looking for each of the names in the div list though, try the following

var all = [];
$(stripped_data).find('div.toppings_name').each(function() {
  var name = $(this).text();
  all.push(name);
});

Upvotes: 3

seeming.amusing
seeming.amusing

Reputation: 1179

You should use jQuery's .each() function in conjunction to get all the values:

$(stripped_data).find('div.toppings_name').each(function() {
    // Process each topping here
});

Upvotes: 3

Related Questions