I am having trouble removing the last DD and DT tags from a definition list when prepending new content using .each. My goal is to remove a set of DD and DT tags with each iteration (as new DD and DT tags are prepended). The following is example code I am using:
shouts_list = $("#shouts dl#shouts_list");
$.each(json.shouts, function (id, shout) {
$("<dt>" + shout.name + "</dt><dd>" + shout.message + "</dd>").hide().prependTo(shouts_list).slideDown('slow', 'swing', function() {
$("#shouts_list > dt:last, #shouts_list > dd:last").slideUp('slow', 'swing');
}).fadeIn();
});
Each time my json object contains multiple items, only one set of DT and DD are removed from the end.
I am learning jQuery and JavaScript slowly and have been stuck on this issue for a while. What would be a good way to remove items from the end of the list for each iteration?
Only one element is being removed from the list because the
eachloop is going through all the items injson.shoutsbefore the firstslideUpcall finishes (ie the loop is too fast or slideUp is too slow). This means that each time this executes:the original last item in the list is always being found, so you’re actually calling
slideUpon the same elementjson.shouts.lengthnumber of times. You need to get all the original items in the list before the each loop starts and count backwards to remove one for each new item added.This should do the trick: