Check if a div exists with jquery

JqueryHtmlExists

Jquery Problem Overview


Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different methods (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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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"

Solution 3 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRafael HerscoviciView Question on Stackoverflow
Solution 1 - Jquerykarim79View Answer on Stackoverflow
Solution 2 - JqueryAlex KeySmithView Answer on Stackoverflow
Solution 3 - JquerytskuzzyView Answer on Stackoverflow