$('#id tag') vs. $('#id').find('tag') - which is preferable?

前端 未结 6 890
情深已故
情深已故 2020-12-10 11:54

I want to know which option is better, particularly in terms of their speed:

$(\'#id tag\')...

or

$(\'#id\').find(\'tag\')         


        
6条回答
  •  不思量自难忘°
    2020-12-10 12:21

    Here's the test case HTML where I look for all span elements under #i element:

    testL1_1 testL1_2
    testL2_1
    • testL3_1
    testL5_1

    Testing these three jQuery selectors:

    $("#i span");         // much slower
    $("#i").find("span"); // FASTEST
    $("span", "#i");      // second fastest
    

    http://jsperf.com/jquery-sub-element-selection

    I've run it on Google Chrome and Firefox and it seems that .find() is the fastest closely followed by the third case and much slower first one.

    jQuery selector performance

提交回复
热议问题