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

I recently had a question on 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 short:

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

One guy I'm working with says the correct way to check should be:

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

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

also:

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

In these types of jQuery functions, it seems that an if check if not required because they will not #myDiv error if #myDiv does not exist, right?

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

+58
javascript jquery
Aug 03 '16 at 18:31
source share
5 answers

One guy I'm working with says the correct way to check should be:

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

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() , ...

+93
Aug 03 '16 at 18:41
source share

This is important, and $( "#myDiv" ).length better because document.getElementById('myDiv') does not work twice. If you cache the selector, this will have a much smaller value:

 var $myDiv = $( "#myDiv" ); if ($myDiv && $myDiv.length) { ... } 

However, jQuery selectors always return what will be interpreted as being "true", therefore

 if ($('#myDiv')) { 

- pointless check.

+27
Aug 03 '16 at 18:33
source share

One guy I'm working with says the correct way to check should be:

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

This statement is false. Checking $( "#myDiv" ).length will simply return 0 if it cannot be found. Of course, here is an example of code with the id found and the second id that is missing:

 console.log("Count of #myDiv found: " + $("#myDiv").length); console.log("Count of #AnotherMyDiv found: " + $("#AnotherMyDiv").length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div id="myDiv"></div> 
+5
Aug 03 '16 at 18:37
source share

Depends on what you do after the if statement.

Think of it this way. Any call to the jquery selector returns a jquery object, which basically represents an array containing many different methods. When you call something like $(".my-elements").show() , it will iterate over all the $(".my-elements") tags and apply .show() to them, and then return the same object jquery, which is a range of jquery.

If you just chain, then no, you don't need to do an if check. Since all subsequent methods will simply execute a loop equivalent to for (var i=0; i<0; i++){ } , which means that nothing will happen. If you have a large chain and you run it in a large loop, which should be very efficient, you can perform an if check, but as a rule, it does not really matter in terms of performance.

If, however, you are doing something that will cause an error or give a bad result, if the element does not exist, then yes, use the if check. For example,

 function addHeight() { var height1 = $("#div1").height(), height2 = $("#div2").height(); $("#otherDiv").css({ top: height1 + height2 }); } 

If div1 or div2 does not exist otherDiv , it will have a top NaN set, which is probably not what you are going to do. In this case, you want to make sure that both div1 and div2 really exist, but you still do not need to check for the presence of otherDiv , because if it does not exist, nothing will happen.

+3
Aug 03 '16 at 19:05
source share

It is easier to check if there is and if we want to get more information from the object, we will not get an error with a null object.

 if (!!$( "#myDiv" )) { //do something } 
-one
Aug 05 '16 at 12:28
source share



All Articles