Do I really need to check if an element exists with jQuery?

后端 未结 5 673
鱼传尺愫
鱼传尺愫 2020-12-24 00:22

I recently had a question about how to correctly check if an element exists with jQuery. I found the answer from here:

https://learn.jquery.com/using-jquery-core/faq

5条回答
  •  余生分开走
    2020-12-24 00:50

    It matters, and $( "#myDiv" ).length is better because it is not running document.getElementById('myDiv') twice. If you were caching the selector, it would matter much less:

    var $myDiv = $( "#myDiv" );
    
    if ($myDiv && $myDiv.length) { ... }
    

    However, jQuery selectors always return something that will be interpreted as "truthy", so

    if ($('#myDiv')) { 
    

    is a pointless check.

提交回复
热议问题