Reputation: 2401
Is it possible to iterate over the value returned by jQuery's $.map
function?
Update: The problem was that I was returning a jQuery object in the first iterator
return $('row').append(generateItem(response.items,item,index));
Once I returned a regular object, it worked fine.
Edit: Thanks to suggestions below, I have figured out how to iterate over the output of a $.map
function. However, I am still unable to manipulate the output of $.map
TLDR; Iteration#1- generateItem()
returns a jQuery object.
Iteration#2 tries to append select portions of the returned jQuery object to DOM elements. This doesn't work.
$($.map(response.items, function(item, index){
// don't wrap this in a $() selector
return generateItem(response.items,item,index);
})).each(function(index,question){
console.log(question)
// => [prevObject: x.fn.x.init[1], context: document, selector: "row", jquery: "1.10.2", constructor: function…]
var container = $('<article>').addClass('row');
// With header, I am trying to grab the jQuery object returned by the $.map function, but it fails
var header = $(question).find('header');
console.log(question) // => x.fn.x.init[0]
var sidebar = $('<section>').addClass('col-md-4 sidebar').html(header);
var body = $(question).find('main.question');
var content = $('<section>').addClass('col-md-8 content').html(body);
var footer = $(question).find('footer');
container = $(container).append(sidebar).append(content).append(footer)
$('main.bottom').append(container);
});
How can I access the returned values of $.map
? $()
doesn't appear to work.
I'm using $.map in an AJAX request. questions
prepares data for DOM insertion by wrapping the data in the appropriate DOM elements. generateItem
is a generic function that preps the data based on whether the item is a question or an answer.
var questions = $.map(response.items, function(item, index){
return generateItem(response.items,item,index);
});
I would like to iterate over questions
so I can add elements to the DOM by section (e.g. add header to the left, main to the right, footer underneath them) for each object. (I do this outside of the first $.map because I don't want to add questions and answers the same way).
The problem is that jQuery's $.map returns a strange object, and I can't access the innerHTML values.
var tidyResponses = $.map(questions, function(question,index) {
console.log(question) => [prevObject: x.fn.x.init[1], context: document, selector: "row", jquery: "1.10.2", constructor: function…]
=> [prevObject: x.fn.x.init[1], context: document, selector: "row", jquery: "1.10.2", constructor: function…]
});
Anyone know what kind of object $.map returns, and how one can interact with it? I tried to use jQuery selectors in tidyResponses
to manipulate each question, but it failed.
Upvotes: 1
Views: 2232
Reputation: 10074
Use $.each
$($.map(function(...) {
return ...;
})).each(function(item) {
// Do something
});
Upvotes: 3