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?
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?
Share Improve this question edited Mar 25, 2013 at 11:21 frenchie 52.1k117 gold badges320 silver badges528 bronze badges asked Mar 25, 2013 at 11:19 Oto ShavadzeOto Shavadze 43k55 gold badges166 silver badges246 bronze badges 3- The .each() function creates a closure: that's what it's all about. – frenchie Commented Mar 25, 2013 at 11:22
-
Nothing to do with the question, but try to use
console.log( $(this).text() );
so that you don't have to click thealert()
away each time. On topic: If you don't need to do certain action on<li>
items, just do$("ul li").empty();
. – user1467267 Commented Mar 25, 2013 at 11:23 -
var myList = []; $("ul li").each(function(){ myList[myList.length] = $(this).html(); }); $("ul li").empty(); console.log(myList);
with this code you will store the innerHTMLs for re-usage and still can empty them all. Might not be what you want, but I'm trying to show workarounds for your (possible) problem. – user1467267 Commented Mar 25, 2013 at 11:29
2 Answers
Reset to default 8The 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.