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
 |  Show 7 more ments

2 Answers 2

Reset to default 7

Use 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