Check if a div exists with 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.
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"