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();
});
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.