Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery each() function

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?

like image 717
Oto Shavadze Avatar asked Mar 25 '13 11:03

Oto Shavadze


2 Answers

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.

like image 148
Frédéric Hamidi Avatar answered Oct 09 '22 00:10

Frédéric Hamidi


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.

like image 23
frenchie Avatar answered Oct 08 '22 23:10

frenchie