JQuery context does not match outermost element

In the following snippet, why is the length equal to 0, when should it 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>
Run codeHide result
+5
source share
4 answers

When you provide a context, you tell jQuery to find the element pinside that context, so your selector will look for a tag pthat is a child of the context.

If you add the container to the context, it will be able to find this 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>
Run codeHide result
+3
source

When you pass a jQuery context, this is equivalent to using a method findthat examines the elements of descendants. From jQuery docs :

.find() $('span', this) $(this).find('span').

p , filter:

jQueryObj.filter("p");

filter , ( , ). (p), .

+2

<p> jQueryObj.

jQueryObj . , :

jQueryObj.find('p');

jquery .find(), $(selector, context), :

.find() $('span', this) $(this).find('span').

:

0

You are looking <p>inside the source<p> ( jQueryObjalready represents the tag <p>).

Since <p>there is no element in the source element <p>, your search returns no results.

0
source

All Articles