Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append element during $.each()

Tags:

jquery

append

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>
like image 846
benedict_w Avatar asked Feb 12 '26 23:02

benedict_w


1 Answers

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.

like image 83
SLaks Avatar answered Feb 15 '26 13:02

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!