Have you ever wanted to check if a element exists using jQuery, but not got the results you were looking for? It’s not as obvious as you might think it is, but when you understand how jQuery treats objects you will never have this problem again.

Let’s look at two different ways of doing it. First we look at the wrong way of doing it, this is probably the way most people think it’s done, because it is logical. But who said everything had to make sense? Then we will look at how it actually is done.

The wrong way of doing it

if($("#yourdiv")) {
// Do some magic
};

This statement will allways return true because jQuery will allways return a object, even if it is an empty one, hence the if-statement is broken and may lead to unexpected results because this will not trigger any error or red blinking lights.

So let’s do it the right way

if($("#yourdiv").length) {
// Do some magic
};

The length property returns the number of elements in the jQuery object, this is what we are looking for. If the object contains no elements the result will be 0 wich will  translate to false in this if-statement.