JQuery.each () chain

I am trying to add results from an object to newly created HTML elements:

*long chain of newly created elements*.append( $("<div />").append( $.each(myObj.results, function( intIndex, objValue ){ return objValue.description; }) ) ); 

If I use a function () call with a for loop instead of each (), it works, but is there no way to achieve this with each ()?

+4
source share
2 answers

.each designed to iterate through a list and perform an operation. You can achieve what you want with $. map . of the returned items at each iteration.

 *long chain of newly created elements*.append( $("<div />").append(function(){ var des = $.map(myObj.results, function( objValue ){ return objValue.description; }); return des.join(' '); }); ); 
+2
source

.each just iterates through the collection, you need an anonymous function to return something, so try the following:

 $("<div />").append(function(){ var string = "": $.each(myObj.results, function( intIndex, objValue ){ string += objValue.description; }) return string; }); 
+3
source

All Articles