Jason
Jason

Reputation: 52533

jQuery: Is there a functional difference between $('.selector', myContext) and myContext.find('.selector')?

I feel like $('.selector', myContext) and myContext.find('.selector') are two identical ways to get the same information. Is there a practical reason when you would use one over the other? Speed perhaps?

Upvotes: 9

Views: 665

Answers (4)

sudip
sudip

Reputation: 2860

When a new jQuery object is created the constructor tries to figure out what was passed in. When context is a DOMElement jQuery transforms $(selector, context) into $(context).find(selector). You can avoid much of the logic the constructor does including some string parsing by making this change yourself. (excerpt from the following post : http://engineeredweb.com/blog/10/12/3-tips-make-your-jquery-selectors-faster/ )

Upvotes: 0

TomWilsonFL
TomWilsonFL

Reputation: 523

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

From: http://api.jquery.com/jQuery/#jQuery1

Upvotes: 3

Joey C.
Joey C.

Reputation: 2376

The first involves slightly less characters of code, but other than that the same thing

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827684

$('.selector', myContext) and $(myContext).find('.selector') are completely equivalent:

From the jQuery 1.4.2 source (core.js):

//...

// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
    return jQuery( context ).find( selector );
}

//...

Upvotes: 10

Related Questions