admin管理员组文章数量:1323342
I have a scenario in which I know that the div I'm looking for is exactly two levels deep.
Is it more efficient to use:
$('#mydiv').find('.myselector')
or
$('#mydiv').children().children('.myselector')
I have a scenario in which I know that the div I'm looking for is exactly two levels deep.
Is it more efficient to use:
$('#mydiv').find('.myselector')
or
$('#mydiv').children().children('.myselector')
Share
Improve this question
edited Jan 27, 2014 at 20:10
j08691
208k32 gold badges269 silver badges280 bronze badges
asked Jan 27, 2014 at 20:02
ForOhForForOhFor
79610 silver badges16 bronze badges
12
- 2 Have you tried it? Should not be to hard to analyze... – Constantinius Commented Jan 27, 2014 at 20:03
- 2 It's more efficient to ditch jQuery. You should always do that if you are looking for efficiency. – bjb568 Commented Jan 27, 2014 at 20:03
- 1 Prepare a test and let people check! jsperf. – Jakub Matczak Commented Jan 27, 2014 at 20:03
- 4 Either way, you'll probably AT MOST shave off a few nanoseconds - I'd say use whichever makes more sense to you and your code... – FastTrack Commented Jan 27, 2014 at 20:05
- 1 @ForOhFor define "significantly" for me if you don't mind... Unless you're cycling through thousands upon thousands of DOM elements, you/your users won't notice a difference. – FastTrack Commented Jan 27, 2014 at 20:06
2 Answers
Reset to default 7Use your console to check. First check your first suggestion:
console.time('benchmark');
for (var i=0; i<1000; i++) {
var $elem = $('#mydiv').find('.myselector');
}
console.timeEnd('benchmark');
Now do the same for your second suggestion:
console.time('benchmark');
for (var i=0; i<1000; i++) {
var $elem = $('#mydiv').children().children('.myselector');
}
console.timeEnd('benchmark');
Run both versions a few times to really check if there is a significant difference. Use this way of testing to optimise your selectors.
Try this instead:
var elems = document.getElementById('mydiv').querySelectorAll(".myselector");
A parison of jQuery versus a few Vanilla JS ideas I had.
EDIT: For IE7 support:
var container = document.getElementById('mydiv'), elems = [],
firstlevel = container.children, l = firstlevel.length,
secondlevel, m, i, j;
for( i=0; i<l; i++) {
secondlevel = firstlevel[i].children;
m = secondlevel.length;
for( j=0; j<m; j++) {
if( secondlevel[j].className.match(/\bmyselector\b/)) {
elems.push(secondlevel[j]);
}
}
}
... Yeah, not pretty! But still faster than jQuery!
本文标签: javascriptJquerychildren()children() vs find()Stack Overflow
版权声明:本文标题:javascript - Jquery - .children().children() vs .find() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742133175a2422252.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论