Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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 pity to see that people do not want to learn what is a 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 is better?

1 Answer

0 votes
by (40.7k points)

If you want to check for the existence of an ID, then there's no need to go into jQuery, you can simply do this:

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

{

}

getElementById returns null if it can't be found.

You can refer to this document for detailed information: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

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.

    }

});

Note: The selector always returns a jQuery object, so there's no need to check against null. If the selector doesn't find anything then length === 0 which is "false" (when converted to bool it is false). Therefore, if it finds something then it should be "truth". 

Related questions

Browse Categories

...