Check if a div exists with jquery

702    Asked by LilyHemmings in Java , Asked on Jun 21, 2021

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() {jquery if div exists
    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');
    }
});

How to Check if a div exists with jquery?

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?

Answered by Aashna Saito

 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 want to check if a div exists with jquery 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.

    }

});



Your Answer

Interviews

Parent Categories