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

前端 未结 6 898
情深已故
情深已故 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:01

    You can base your decision on 3 things:

    Readability

    This is not much of a difference with your two given selectors. For my part, I prefer the $('#id').find('inner') syntax because it describes more accurately what it is actually doing.

    Reusability

    If you have other parts of your code use the same id selector (or something in its context), you can cache the selector and reuse it. I myself find it harder to refactor code that has been written like this $('#id inner'), because you have to decode the css selector first before you can move on and find possible improvements.

    Imagine these two cases with not much complexity

    $('#hello .class_name tag').doThis();
    $('#hello .other_name input').doThat();
    

    And the other case

    $('#hello').find('.class_name tag').doThis();
    $('#hello').find('.other_name input').doThat();
    

    I think the second example screams at you «Cache the id selector», and the first does not.

    Speed

    Performance is always a good point, and in this case, the id selector with the find does the better job in most browsers, because it establishes the context first and can apply the descending selector to a smaller subset of elements.

    Here's a good performance test, if you want to know more about context-vs subset selectors performance in jQuery. Subsets of ids generally rule. Of course you can get different results, but in most cases, they do.

    So, 3 to 0 for subset selectors from my point of view.

提交回复
热议问题