This list
<ul> <li>aaa</li> <li>sss</li> <li>ddd</li> </ul>
js code:
$(document).ready( function () { $("ul li").each( function () { $("ul").empty(); alert( $(this).text() ); }); });
This code returns every item usually, why? Why is the list not cleared at the first iteration?
The unordered list is indeed cleared at the first iteration, but the list items still reference the jQuery object created with $("ul li").
$("ul li")
They can no longer be part of the DOM, but they still exist in memory, and you can still access and manipulate them.
The function .each()creates a closure: that all closure.
.each()
$("ul").empty();, , ALSO this, , $("ul li") .
$("ul").empty();
this