u936293
u936293

Reputation: 16264

Contextual jQuery selector does not find some elements, why?

If I understand the context parameter correctly as described in the documentation, p in the following is a collection of two items as expected:

const text = "<body><div class='a'> <p>Test</p> <p>Test 2</p> </div></body>";
const p = $("p", text);

But why do the following all return no results?

const d = $("div", text);
const b = $("body", text);

JS Fiddle

Upvotes: 4

Views: 35

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337620

If you look at the outerHTML of the jQuery object which gets created from text, you'll see that the body element is removed. This is because you cannot append a body element using jQuery. One should already be present in the DOM, and you cannot append another.

Therefore there is no body element to find within the text jQuery object. Here's an demo of that:

const text = $("<body><div class='a'> <p>Test</p> <p>Test 2</p> </div></body>");
console.log(text[0].outerHTML) // no body!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

As you can see in the above output, the div then becomes the root element of the jQuery object.

From there you're effectively then performing $('div').find('div') - ie. trying to look for the element within the element that contains it. As such nothing is returned.

Upvotes: 3

Related Questions