[jquery] Check if a div exists with jquery

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?

This question is related to jquery html exists

The answer is


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.


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.


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"


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to exists

Select rows which are not present in other table How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error? Check if record exists from controller in Rails sql: check if entry in table A exists in table B How to exclude records with certain values in sql select SQL - IF EXISTS UPDATE ELSE INSERT INTO Linq select objects in list where exists IN (A,B,C) PL/pgSQL checking if a row exists How to Check if value exists in a MySQL database MongoDB: How to query for records where field is null or not set?