When using jQuery (or any other JavaScript library for that matter), have you ever wondered how to test whether an element exists using a selector? Well, maybe you haven’t, but I have – lots of times – so I thought I’d share how it’s done here because it’s not as simple as it seems.
The obvious thing would simply be to wrap a selector in an 
if statement, right?
if ($("#mydiv")){
    // do something here
}
Well, wrong – that won’t work! When you use a selector, jQuery will 
always return an object. Therefore the 
if statement will always be true and never be false. In the case of an element that does not exist on the page, jQuery will return an object with nothing in it – an empty object. And therein lies our solution.
With a jQuery selector we can also use the 
length property, which will return the size of the object. Do you see where I’m heading with this? That’s right, lets just change our 
if statement to:
if ($("#mydiv").length > 0){
    // do something here
}
Now our code works because when jQuery returns an empty object, the 
lengthproperty will return zero and therefore the 
if statement will be false. Hurrah!