Using the Context Parameter - J Query

You’ve heard of the context parameter but have yet to encounter a situation where it’s useful.


As well as passing a selector expression to jQuery() or $(), you can pass a second argument that specifies the context. The context is where jQuery will search for the elements matched by your selector expression.
The context parameter is probably one of the most underused of jQuery’s features. The way to use it is incredibly simple: pass a selector expression, a jQuery object, a DOM collection, or a DOM node to the context argument, and jQuery will search only for elements within that context.
Here’s an example: you want to select all input fields within a form before it’s submitted:

Notice that this was passed as the second argument; within the handler just shown,this refers to the form element. Since it’s set as the context, jQuery will only return input elements within that form. If we didn’t include that second argument, then all of the document’s input elements would be selected—not what we want.
As mentioned, you can also pass a regular selector as the context:

The preceding code returns exactly the same collection as the following selector:

Specifying a context can aid in readability and speed. It’s a useful feature to know about!

The default context used by jQuery is document, i.e., the topmost item in the DOM hierarchy. Only specify a context if it’s different from this default. Using a context can be expressed in the following way:

In fact, this is exactly what jQuery does behind the scenes.
Considering this, if you already have a reference to the context, then you should pass that instead of a selector—there’s no point in making jQuery go through the selection process again.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics