views:

32

answers:

2

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?

+5  A: 

You need to use .filter() instead.

This will filter through items at the top level of the jQuery object.

myJq.filter(".a")
patrick dw
Awesome. Thanks!
morgancodes
@morgancodes - You're welcome. :o)
patrick dw
+2  A: 

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.

jAndy
True. Grabbing by index would be faster than by selector, but more fragile/higher maintenance if the structure changes. +1
patrick dw