quuxbazer
quuxbazer

Reputation: 551

jQuery selector context doesn't match outermost element

In the following snippet, why is the length is 0 when it should be 1?

var jQueryObj = $("<p>testing</p>");
// Display the length
$('body').html($("p", jQueryObj).length);
<script src="http://code.jquery.com/jquery-2.2.0.js"></script>

Upvotes: 4

Views: 1934

Answers (4)

Rafay
Rafay

Reputation: 31043

When you provide the context, you are telling jQuery to find the p element inside that context, so your selector will look for any p tag that is a child of the context.

If you add a container to the context, it will be able to find that element.

var jQueryObj = $("<div><p>testing</p></div>");
// Display the length
$('body').html($("p", jQueryObj).length);
<script src="http://code.jquery.com/jquery-2.2.0.js"></script>

Upvotes: 2

Tadeck
Tadeck

Reputation: 137410

You are searching for <p> inside your original <p> (jQueryObj already represents a <p> tag).

Because there is no <p> element within your original <p> element, your search does not return any results.

Upvotes: 0

Didier Ghys
Didier Ghys

Reputation: 30666

There is simply no <p> element within you jQueryObj.

Using jQueryObj as a context will limite the search for the provided selector to the context. It is the same as writing:

jQueryObj.find('p');

Internally, jquery actually uses .find() when you use the syntax $(selector, context), as stated in the doc:

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

Further reading:

Upvotes: 0

James Allardice
James Allardice

Reputation: 166021

When you pass a context to jQuery, it's equivalent to using the find method, which looks at descendent elements. From the jQuery docs:

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

Your p element is not a descendant, so you would need to use filter:

jQueryObj.filter("p");

The filter method reduces the matched set of elements to those that match the selector (or pass a test defined by a function). In your case, the matched set of elements contains one element (the p), which will match the selector.

Upvotes: 2

Related Questions