jQuery.find() ignores root node

2020-02-11 01:32发布

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?

3条回答
▲ chillily
2楼-- · 2020-02-11 02:10

You need to use .filter() instead.

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

myJq.filter(".a")
查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-11 02:20

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.

查看更多
我命由我不由天
4楼-- · 2020-02-11 02:32

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/

查看更多
登录 后发表回答