简体   繁体   中英

Jquery - .children().children() vs .find()

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')

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 comparison 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM