0

I use a simple for loop in jQuery. In the example below, if I delete the line calling the .remove() function, console.log outputs all elements. But if I add the call to .remove() it doesn't log all the elements anymore.

What am I doing wrong?

Note:

I know I can use $('.list').remove() to remove all elements, but this just an example. I would like to know the reason why the loop doesn't run as expected.

I also tried the .each() function and it worked fine. But I want find a solution with the for loop.

http://jsfiddle.net/53HzV/1/

$('.btn').click(function(){
    for (var i = 0; i < $('.list').length; i++) {
        console.log($('.list').eq(i));

        $('.list').eq(i).remove();
    }
});


<div class="list">list</div>
<div class="list">list</div>
<div class="list">list</div>
<div class="list">list</div>

<div class="btn">btn</div>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user1775888
  • 3,147
  • 13
  • 45
  • 65
  • 4
    You know you could just do `$('.list').remove()`. You're dealing with collections, that's what jQuery is all about. – elclanrs Jul 04 '14 at 01:04
  • @elclanrs thanks for reply! this is example.. I use it in my function add other function... `You're dealing with collections ` ?? – user1775888 Jul 04 '14 at 01:06
  • 1
    Save `$('.list')` in a variable before the loop and it will work. Right now you are mutating the collection you are iterating over, which, as you noticed, can cause problems. – Felix Kling Jul 04 '14 at 01:06
  • @karthikr why? the loop start from index 0 – user1775888 Jul 04 '14 at 01:08
  • 1
    It's Python, but it's the same issue and nicely demonstrated: http://stackoverflow.com/q/6500888/218196 – Felix Kling Jul 04 '14 at 01:13

2 Answers2

4

Here is what your code is doing:

First loop: i=0, 4 divs (length=4), remove the first one (index 0)

Second loop: i=1, 3 divs (length=3), remove the second one (index 1)

Third loop: i=2, 2 divs (length=2), do nothing as i=length

Obviously your code will break at the third loop.

Christophe
  • 27,383
  • 28
  • 97
  • 140
-1

The best way is to restructure your code and use some features of jQuery you're not employing yet. If the idea is to remove each class=list element when the button is clicked, you could do the following:

$('.btn').click(function(){
  $('.list').each(function() {
    $(this).remove();
  });
});

This method will allow you to add in logic, if desired in the future, to check each element prior to removing it.

Your loop isn't working, because you are accessing the element to delete using the i variable and the length of the list is changing each iteration through the loop. So, in your case, since there are 4 items (meaning indexes 0-3 using .eq(i) in the loop), once you delete the first two (and i=2), $('.list').length no longer evaluates to 4, but is 2 now, so the loop exits. You'll always only remove half the items with that loop structured that way.

David Atchley
  • 1,204
  • 8
  • 10