Eric Eric - 6 months ago 30
jQuery Question

Why is .detach() throwing error in array of DOM elements?

I'm wondering why I'm getting error "$groceryItems[i].detach is not a function" when I'm able to see that $groceryItems[i] is indeed a DOM element as a result of logging it?

I have only included the script and not the ejs view.

<script>
function sortByAvgRating() {

var $groceryItems = $('.groceryItems');//grab all of the grocery items

for (var i = $groceryItems.length; i--; ) {//detach each grocery item from the DOM
console.log('$groceryItems[i] ', $groceryItems[i]);
$groceryItems[i].detach();
}

$groceryItems.sort(function(a, b) {//sort the grocery items by the rating attribute
return +a.children[1].children[0].children[0].dataset.rating -
+b.children[1].children[0].children[0].dataset.rating;
}).
appendTo('groceryItemsContainer');//apppend the sorted array of elements to the DOM
}

</script>

Answer Source

@ibrahim mahir's answer explains why your code doesn't work.

But you don't need to write a loop to detach all the elements in a jQuery object. When you apply jQuery modification functions to a collection, it automatically performs it on all elements.

So you can simply write:

$groceryItems.detach();

And when you want to loop over the elements in a collection, use .each():

$groceryItems.each(function() {
    console.log(this);
    $(this).detach();
});