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?
Geuis source share