Jquery each () function

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?

+5
source share
2 answers

The unordered list is indeed cleared at the first iteration, but the list items still reference the jQuery object created with $("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.

+8
source

The function .each()creates a closure: that all closure.

$("ul").empty();, , ALSO this, , $("ul li") .

+1

All Articles