开发者

Check if a div exists with jquery [duplicate]

开发者 https://www.devze.com 2023-03-24 02:07 出处:网络
This question already has answers here: Is there an "exists" function for jQuery? (47 answers)
This question already has answers here: Is there an "exists" function for jQuery? (47 answers) Closed 3 years ago.

Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different meth开发者_开发百科ods (listed below)

$(document).ready(function() {
    if ($('#DivID').length){
        alert('Found with Length');
    }

    if ($('#DivID').length > 0 ) {
        alert('Found with Length bigger then Zero');
    }

    if ($('#DivID') != null ) {
        alert('Found with Not Null');
    }
});

Which one of the 3 is the correct way to check if the div exists?

EDIT: It's a pitty to see that people do not want to learn what is the better approach from the three different methods. This question is not actually on "How to check if a div exists" but it's about which method is better, and, if someone could explain, why it it better?


The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.


If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"


As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号