Determining the Exact Query That Was Used - J Query

While writing a plugin or a method that extends jQuery, you need to know exactly what the selection and the context used when calling the method so that the method can be recalled.


We can use the core properties .selector and .context in conjunction with each other so we can re-create the original query that was passed through. We need to use both in conjunction because not all queries to our function or plugin will be within the default document context:


Figure : shows the output.


In the preceding example, we define a method that can be called from a jQuery selection, ShowQuery. Within that method, we alert the query as it was passed in and then recursively recall ShowQuery again with the same jQuery selector. The if statement is there so that we don’t get into a recursive loop.
The core properties .selector and .context were introduced in jQuery 1.3, which was released in January 2009. These methods are geared more toward plugin developers who may need to perform an action against the original query passed in. A potential use case of using these methods is to rerun the selection query or to check to see whether an element is in the selection.

  • selector returns as a string the actual selector that was used to match the given elements. selector will return the whole selector if, say, the selection is broken up where there is a selector and then the matched set is narrowed with the use of the find() method:

  • context will return the DOM node originally passed in to jQuery(). If no context was set in the selector, the context will default to the document.

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

J Query Topics