Use jQuery’s $.closest() vs $.parents()

Sam Deering
Share

So I guess you should consider using $.closest() instead of $.parents(). But first, as always you need to know what your dealing with – the key difference between them.

.closest() .parents()
Begins with the current element Begins with the parent element
Travels up the DOM tree until it finds a match for the supplied selector Travels up the DOM tree to the document’s root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
The returned jQuery object contains zero or one element for each element in the original set The returned jQuery object contains zero or more elements for each element in the original set

This jsperf shows the speed results.

22-04-2013 12-09-37 AM

Get parent container using $.parents()

Code example.

//remove handler
$('.btn.remove').on('click', _this.cache.$container, function(e)
{
     e.preventDefault();
     console.log('remove...');
     $(this).parents('li').first().remove();
});

Get parent container using $.closest()

Code example.

//remove handler
$('.btn.remove').on('click', _this.cache.$container, function(e)
{
     e.preventDefault();
     console.log('remove...');
     $(this).closest('li').remove();
});