Context vs. Selector specific in jQuery

There are cases when you can specify the area in which a particular element can be found either using a hierarchical selector, that is:

$('#someParent .someChildren') 

... or using context, i.e.:

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

I know that there are times when you cannot use the former, so obviously the latter is useful. But in situations like the one I imagine, which is better and why?

+4
source share
2 answers

It:

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

just converts to this:

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

after doing some tests. Thus, the actual review will be between:

 $('#someParent .someChildren') 

and

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

(taking into account the work of analysis and transformation).

So which of these two is faster is probably browser dependent. I personally never use the context parameter.

If you want .find() , I would just use it directly, instead of jQuery flipping it for you.

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

 $('.someChildren', this) 

... so in this case it’s faster to do this:

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

... and more understandable in my opinion.

+3
source
  // 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 source

here we see that use

$("#foo .bar") comes down to $(document).find("#foo .bar")

$(".bar", $("#foo")) comes down to $("#foo").find(".bar")

It's hard to say which is more efficient. Either sizzle is slow, that the descendant selector, or calling $(..) is twice as slow. It really requires benchmarking. Also note that $(document) cached as rootjQuery

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

+2
source

Source: https://habr.com/ru/post/1342164/


All Articles