My jQuery object looks like this:
var myJq = jQuery("<div class='a'></div><div class='b'></div>")
myJq.find(".a")
returns an empty jQuery object, apparently because find()
searches only the children of the nodes contained in a jQuery object, not the nodes themselves.
How can I grab one of the divs in myJq
using a selector?
You need to use
.filter()
instead.This will filter through items at the top level of the jQuery object.
You can either use
.filter()
or (better, faster) use
.first()
Benchmark
.first()
is about 8x faster for me.Here's a .find2() that'll find both root elements and children:
With this, you can do:
Here's more about it: http://danielnouri.org/notes/2011/03/14/a-jquery-find-that-also-finds-the-root-element/