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.
$('.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>