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

后端 未结 5 659
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    2020-12-24 00:59

    One guy I work with says the correct way to check should be:

    if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
        //do something 
    }
    

    This statement is false. The check of $( "#myDiv" ).length would simply return 0 if it's not found. To be sure, here's a code example with both an id found, and a second id that's not present:

    console.log("Count of #myDiv's found: " + $("#myDiv").length);
    console.log("Count of #AnotherMyDiv's found: " + $("#AnotherMyDiv").length);
    
    

提交回复
热议问题