Jason Z Jason Z - 4 months ago 19
Javascript Question

Do I really need to check if an element exists with jQuery?

I recently had a question about how to correctly check if an element exists with jQuery. I found the answer from here:

https://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

In summary:

if ( $( "#myDiv" ).length ) {
// Do something
}


One guy I work with says the correct way to check should be:

if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
// Do something
}


Does it matter? I mean from a performance or latency wise, do they perform the same?

Also:

$( "#myDiv" ).show();
$( "#myDiv" ).hide();
$( "#myDiv" ).val('');


In these type of jQuery functions, it seems no
if
check is needed because they won't raise an error if
#myDiv
does not exist, correct?

For what it's worth, I am using jQuery 1.6.4.

Answer

One guy I work with says the correct way to check should be:

if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
    //do something
}

He's wrong, at least in terms of the $( "#myDiv" ) && part. jQuery's $(selector) always returns an object, which by definition is truthy. So that part is pointless, and re-querying the DOM for no reason.

I mean from a performance or latency wise, do they perform the same?

Re-querying the DOM for no 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") which are optimized by jQuery into calls to getElementById (which is blazingly-fast). So on the one hand, yes, it's wasteful extra work. On the other hand, browsers are so fast these days that you probably have bigger fish to fry. But it's probably extra pointless code, which is the larger issue.

To the general point: jQuery is set-based. This means that operations on sets with no elements in them are no-ops. E.g.:

$(".foo").addClass("bar");

...is a no-op (not an error) if no .foo elements are in the DOM.

So check for length if and when you care whether you matched elements. If you don't care and just want to perform operations on them if they're there, just go ahead and do the operation.

So basically, there are three scenarios:

  1. You know the elements will be there, so the check is pointless
    => no check

  2. You don't know the elements will be there, but you don't care and just want to operate on them if they're there
    => no check

  3. You care whether the elements are there for some other reason
    => do the check