Eric Eric - 1 year ago 55
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.

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.sort(function(a, b) {//sort the grocery items by the rating attribute
return +a.children[1].children[0].children[0].dataset.rating -
appendTo('groceryItemsContainer');//apppend the sorted array of elements to the DOM


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:


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

$groceryItems.each(function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download