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
Depends on what you're doing after the if statement.
Think of it like this. Any jquery selector call returns a jquery object that's basically an array extended with a bunch of different methods. When you call something like $(".my-elements").show() it'll loop over whatever elements $(".my-elements") returned and apply .show() to them then return that same jquery object which is how jquery chains.
If you're just doing chainable things then no, you don't need to do the if check. Because all the subsequent methods will just do a loop equivalent to for (var i=0; i<0; i++){ } which means nothing will happen. If you've got a big chain and you're running it in a big loop that needs to be very performant, you might want to do the if check, but generally it won't really matter from a performance standpoint.
If however, you're doing something that will throw an error or give you a bad result if the element doesn't exist then yes, use the if check. For instance
function addHeight() {
var height1 = $("#div1").height(),
height2 = $("#div2").height();
$("#otherDiv").css({ top: height1 + height2 });
}
If div1 or div2 don't exist otherDiv will get it's top set to NaN which is probably not what you're going for. In this case you would want to verify that both div1 and div2 actually exist, but you still don't really have to check for otherDiv because if it doesn't exist nothing will happen anyway.