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.
J Query Related Interview Questions
|HTML 4 Interview Questions||HTML Interview Questions|
|HTML 5 Interview Questions||Zend Interview Questions|
|JqueryUI Interview Questions||Dynamic HTML Interview Questions|
|XQuery Interview Questions||jQuery Mobile Interview Questions|
J Query Related Practice Tests
|HTML 4 Practice Tests||HTML Practice Tests|
|HTML 5 Practice Tests||Zend Practice Tests|
|PHP and Jquery Practice Tests||J Query Practice Tests|
|CodeIgniter Practice Tests||Dynamic HTML Practice Tests|
J Query Tutorial
Selecting Elements With Jquery
Beyond The Basics
Faster, Simpler, More Fun
Html Form Enhancements From Scratch
Html Form Enhancements With Plugins
Interface Components From Scratch
User Interfaces With Jquery Ui
Jquery Ui Theming
Jquery, Ajax, Data Formats: Html, Xml, Json, Jsonp
Using Jquery In Large Projects
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.