jackdaw
jackdaw

Reputation: 2314

Length of jQuery collection object doesn't change after calling detach() on an element

This seems incredibly simple but I cannot understand why it doesn't work.

$('.some-containers').each(function () {

    var $ul = $(this).find('ul');

    var $items = $ul.find('li'); 
    console.log($items.length); //5

    if ($items.length > 2) {
        var $last = $items.last().detach();
        console.log($items.length); //still 5
    }

}

My question is why, after removing or detaching the last item, is the last item still there?

Upvotes: 4

Views: 638

Answers (1)

ElGavilan
ElGavilan

Reputation: 6914

Think of $items as a copy of the element collection in the DOM, instead of a reference. detach() operates on the DOM, and removes the specified element from the DOM.

Reassign $items to the collection again:

$items = $ul.find('li');

or just do $ul.find('li').length and the length will reflect the actual value.

Example (thanks @MartinGottweis): https://jsfiddle.net/j7hqnhb3/

Upvotes: 4

Related Questions