开发者

Context vs. Selector specificy in jQuery

There are times when one can specify the scope in which a particular element might be found either by using a hierarchical selector, ie:

$('#someParent .someChildren')
开发者_运维技巧

...or by using context, ie:

$('.someChildren', $('#someParent'))

I know there are times when one can't use the former, so obviously the latter is useful. But in situations like the one I present, which is better and why?


This:

$('.someChildren', $('#someParent'))

is simply converted into this:

$('#someParent').find('.someChildren')

after running some tests. So the actual consideration will be between:

$('#someParent .someChildren')

and:

$('#someParent').find('.someChildren')

(taking into consideration the work of analyzing and converting).

So which of those two is faster will likely be browser dependent. I personally never use the context parameter.

If you want a .find(), then I'd just use it directly instead of having jQuery flip it for you.

People often use the context when the need to set this as the root of the .find().

$('.someChildren', this)

...so in that case, it is faster to do this:

$(this).find('.someChildren')

...and more easily understandable in my opinion.


    // HANDLE: $(expr, $(...))
} else if (!context || context.jquery) {
    return (context || rootjQuery).find(selector);
    // HANDLE: $(expr, context)
    // (which is just equivalent to: $(context).find(expr)
} else {
    return this.constructor(context).find(selector);
}

From the source

here we can see that using

$("#foo .bar") reduces to $(document).find("#foo .bar")

$(".bar", $("#foo")) reduces to $("#foo").find(".bar")

It's hard to tell which is more efficient. Either sizzle is slow with that descendent selector or having to call $(..) twice is slower. This does indeed require benchmarking. Also note that $(document) is cached as rootjQuery

As @patrick_dw mentioned it's probably better to compare it to $("#foo").find(".bar") directly instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜