Nov
20
2011

How to check whether an element exists with jQuery

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.

About the Author: SGH

At the same time, I can’t think of anything more satisfying than sitting in front of TV, eating take-away, lights down low, in my pyjamas and watching crap on TV. Basically, I strive to live a balanced life. Fun. Serious. Fast. Slow. Brainy. Bimbotic. Intense. Lazy. You get the drift.

1 Comment: + Add Comment

  • 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 comment

Click to refresh

Subscribe to newsletter

Sign up with your email to get updates about new resources releases and special offers.