When we 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.

if ($("#div_id")){
  // code goes here
}

What’s wrong – it will not 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.

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 ($("#div_id").length > 0){
  // code goes here
}

Now it works because when jQuery returns an empty object, the length property will return zero and therefore the if statement will be false.

0 Shares:
0 comments
  1. This would be a very useful itodein, allowing much cleaner html with less serverside scripting. Right now we build css-classes into the server side scripts to achieve this kind of design, but as you say it could easily be done using CSS.Great idea!

Leave a Reply

Your email address will not be published. Required fields are marked *

15 − 8 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like