Coming to jQuery from a functional background, I am fond (perhaps unreasonably so) of elegant chains of functions. I often find myself dealing with arrays of elements, such as those that may result from $.map, and my ability to manipulate these arrays in the DOM seems quite limited. Here’s some sample code that runs through the results of a Google search, rendering the result titles:
var newResultsDiv = $('<div id="results" />');
$.each(searcher.results, function() {
newResultsDiv.append('<p>' + this.title);
});
$("#searchresults").append(newResultsDiv);
I find this excessively verbose. Ideally, I would do something along these lines instead:
$.map(searcher.results, function(elem) {
return $('<p>' + elem.title);
}).wrapAll('<div id="results" />').appendTo('#searchresults');
I’ve tried this out, along with several variants using different forms of append and wrap. They all appear to be incapable of handling the plain-old-Javascript array that jQuery.map spits out. They’re designed to work with jQuery’s own set collection. At least, that’s my guess, as messing around with these functions in the Firebug console seems to confirm the problem.
I am hoping that someone here has the wisdom to show me an elegant way to do what I’m trying to do. Is there one?
Using the
$.mapmethod you presented, you could return the actual DOM element instead of a jQuery object. This is done by grabbing the[0]index item in the jQuery object. Then wrap the entire$.mapwith$().This works because jQuery will accept an array of DOM elements.
Your
<p>creation was a little off. I changed it to pass an object literal to set the text. Otherwise, you would need to concatenate the ending tag as well.Finally, you would need to traverse up to the wrapper
#resultsyou created using.parent().EDIT: IF you don’t mind the look of it, you could do this as well: