I’m trying to repeatedly append an element defined outside the closure in a jQuery $.each() loop see – http://jsfiddle.net/benedict_w/8Pczs/
Could someone please explain why the element is only appended in the last iteration of the loop?
e.g.
<ul>
<li>blah</li>
<li>blah</li>
<li>blah</li>
</ul>
using the following jquery:
var remove = $('<a href="#">remove</a>');
$('li').each(function(){
$(this).append(remove);
});
producers:
<ul>
<li>blah</li>
<li>blah</li>
<li>blah <a href="#">remove</a></li>
</ul>
You’re appending the same element each time.
Each append will move it to the next
<li>.You need to
clone()the element (or just re-create it) for each iteration.