I’ve got a data set that’s retrieved by an ajax call, i’m looping over the data set and for each item in the set append a <li> to a list that’s on the page.
how can I get a hold of the appended listitem in the each-loop so I can also perform individual actions on that
var myData = getData();
var list = $('#list');
$.each(myData, function(index, person){
list.append('<li>'+person.name+'</li>');
// On the just appended <li> element I want to set the data-person attribute
//var listitem = ???;
//listitem.data('person', person);
});
Here’s a fiddle to illustrate my problem: http://jsfiddle.net/pcLt7/1/
Just create a jQuery object from the raw HTML and then append that
Note: It’s not a good idea to do DOM manipulation inside a loop.
If the number of elements is small then just use my solution. If this could be hundreds of elements, you may want to work on detached nodes by using detach on the list before adding the items and later adding it to the DOM again.
Don’t optimize prematurely. The solution uses less code and is more readable than any other and works just fine.