jQuery: the selector and context properties

Each jQuery selector expression comes equipped with two important properties, namely selector and context. The former returns the string representation of the CSS selectors used in the query, while the latter displays the context where this query takes place, starting with the global HTMLDocument DOM object. For example, suppose that we have the following DOM structure:

<div id="test">



A simple selector expression would be the following:

var $p = $('p', '#test');

which generates the following values stored in selector and context:

alert($p.selector); // #test p
alert($p.context);  // [object HTMLDocument]

The selector property returns what we expect, but the context property returns the whole document object. To get more consistent results, we have to pass a DOM expression to our context parameter:

var $p2 = $('#test p', document.body);
alert($p2.context); // [object HTMLBodyElement]

As you can see, now the context is what we did want.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.