Given 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 element normally, Why? Why list is not cleared at first iteration?
The unordered list is indeed cleared in your first iteration, but the list items are still referenced by the jQuery object you created with $("ul li")
.
They may not be part of the DOM anymore, but they still exist in memory, and you can still access and manipulate them.
The .each()
function creates a closure: that's what closures are all about.
When the line $("ul").empty();
executes, it clears the reference to the list but because the same list is ALSO referenced with this
, the list is still there, just not referenced with $("ul li")
anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With