Xerion
Xerion

Reputation: 3281

Is jQuery('.foo').find('.bar') equivalent to jQuery('.bar', jQuery('.foo'))?

Using:

var $a = $('.foo').find('.bar');

var $b = $('.bar', $('.foo'));

I know $b will have its context set to $('.foo'), while $a. Aside from that, I believe the two objects are the same, correct?

Follow up Qs:

  1. Will the perf be the same as well since the search is rooted off of the same object effectively?
  2. Does a more strict context improve perf in terms of core jquery operations at all? (I know it's intended for plugin usage.)

Thanks!

Upvotes: 1

Views: 642

Answers (2)

Russ Cam
Russ Cam

Reputation: 125518

EDIT:

yes, they are equivalent, here's the source

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

To use context effectively, it needs to be an HTMLElement, otherwise the context is document

find() is implemented as such in jQuery 1.3.2

find: function( selector ) {
    if ( this.length === 1 ) {
        var ret = this.pushStack( [], "find", selector );
        ret.length = 0;
        jQuery.find( selector, this[0], ret );
        return ret;
    } else {
        return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
            return jQuery.find( selector, elem );
        })), "find", selector );
    }
}

find() uses the Sizzle selector engine to do the actual finding work (take a look at line 2364 in the jQuery source).

and pushStack is

// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
    // Build a new jQuery matched element set
    var ret = jQuery( elems );

    // Add the old object onto the stack (as a reference)
    ret.prevObject = this;

    ret.context = this.context;

    if ( name === "find" )
        ret.selector = this.selector + (this.selector ? " " : "") + selector;
    else if ( name )
        ret.selector = this.selector + "." + name + "(" + selector + ")";

    // Return the newly-formed element set
    return ret;
}

Brandon Aaron has written a great article on understanding the context in jQuery

Upvotes: 4

John Fisher
John Fisher

Reputation: 22717

Yes, the results would be the same. Performance should be identical as well, but that's what testing is for!

There is a property on the resulting jQuery object which shows the selector used to find the matches. Check it out in your debugger. They may even be the same between the two methods.

Upvotes: 0

Related Questions