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.
myJq.filter(".a")
Here's a .find2() that'll find both root elements and children:
$.fn.find2 = function(selector) {
return this.filter(selector).add(this.find(selector));
};
With this, you can do:
var html = '<div class="one"><div class="one"></div></div>';
var el = html.find2(".one"); // will match both divs
Here's more about it: http://danielnouri.org/notes/2011/03/14/a-jquery-find-that-also-finds-the-root-element/
You can either use .filter()
var div = myJq.filter('.a');
or (better, faster) use .first()
var div = myJq.first('.a');
Benchmark
var myJq = jQuery("<div class='a'></div><div class='b'></div>")
var loop = 20000;
console.time('filter');
while(loop--){
var blah = myJq.filter(".a");
}
console.timeEnd('filter');
loop = 20000;
console.time('first');
while(loop--){
var blah = myJq.first(".a");
}
console.timeEnd('first');
.first()
is about 8x faster for me.