One guy I'm working with says the correct way to check should be:
if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
He is mistaken, at least in part $( "#myDiv" ) && . jQuery $(selector) always returns an object, which by definition is true. So this part is pointless and re-query the DOM for no reason.
I mean from performance or latency, do they do the same?
Retrying the DOM for any reason is a waste, but most of the time it doesn't matter in any observable way, and especially not for ID selectors like $("#myDiv") that jQuery optimizes into getElementById calls (which is incredibly fast). So, on the one hand, yes, this is wasteful extra work. Browsers, on the other hand, are so fast these days that you probably have big fish to fry. But this is probably superfluous pointless code, which is a bigger problem.
To a common point: jQuery is set-based. This means that operations on sets without elements in them are not operations. For example:.
$(".foo").addClass("bar");
... is no-op (and not an error) if there are no .foo elements in the DOM.
So, check length if and when you care about the consistent elements. If you donβt care and just want to perform operations on them, if any, just go ahead and complete the operation (with one important caveat 1 ).
Basically, there are three scenarios:
You know that the elements will be there, so the check is useless - => no check
You do not know what elements will be there, but you do not care, and just want to work with them if they are there, = => no check
Do you care if elements exist for any other reason
=> perform check
1 Here's an important caveat: if you call a jQuery function that returns something other than a jQuery object (like val() or offset() or position() , etc.) when you call it on an empty set, it usually returns undefined (the exception is text() , which will return "" [ text() ] unlike the others in several ways: this is one of them]). So writing code that naively assumes these things will return what you expect, even when the kit is empty, will bite you.
So for example:
if ($(".foo").offset().top > 20)
... will throw an error if there are no .foo elements, because offset() will return undefined , not an object.
But this is wonderful:
$(".foo").closest(".bar").toggleClass("baz"):
... because even if there is no .foo , closest() will return another empty jQuery set, and the call toggleClass() on it is no-op.
Therefore, when you are dealing with an accessory that does not return a jQuery object, if you do not know for sure that you are dealing with a set containing at least one element, you need additional protection, for example:
var offset = $(".foo").offset(); if (offset && offset.top > 20)
Again, most accessories (which do not return jQuery objects) do this, including val() , offset() , position() , css() , ...