Why doesn't the following jQuery selector return both elements?

I came across a situation where I create a jQuery object from an html string and have to select all the elements inside it with a specific class.

What I find strange is that it returns one or the other, depending on what type of selection mechanism I use. Here is a test case:

var tmpl = '<ul><li class="foo">TEST</li></ul><div class="foo">BAR</div>'; console.log( $('.foo', tmpl) ); //[<li class="foo">TEST</li>] console.log( $(tmpl).find('.foo') ); //[<li class="foo">TEST</li>] console.log( $(tmpl).filter('.foo') ); //[<div class="foo">BAR</div>] 

http://jsfiddle.net/Rfq9F/

In this example, both the li element in ul and the div without children have the class "foo". In this example, I use the .foo selector and set the context for the template string. Secondly, I use .find () in a string. Finally, I use .filter () in the string.

Can someone explain why the selector mechanisms act the way they are, as well as how to achieve the goal that I mentioned at the beginning?

+6
source share
2 answers

This is because it is not one root of the node, but two ( ul and div ).

Wrap everything in a <div> and it will work:

http://jsfiddle.net/Rfq9F/3/

+7
source

Calling $(tmpl) creates a set with two elements - the <ul> element and the <div class="foo"> element. .find() searches for elements that are descendants of any of the elements in the set that match the selector. .filter() returns any elements in the set that match the selector.

The first two lines:

 console.log( $('.foo', tmpl) ); console.log( $(tmpl).find('.foo') ); 

equivalent, these are just two different ways to write the same thing.

+2
source

Source: https://habr.com/ru/post/910581/


All Articles