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.

  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 *

5 × two =

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

You May Also Like

qTip2 – Advanced jQuery Tooltip Plugin

qTip2 plugin can display the tooltip in any position wanted, plays nicely with image maps and they can be set to follow any element (handy for drag 'n' dropped and animated items) or mouse.

Really Simple Slideshow – A Flexible Slider Plugin

Really Simple Slideshow is a jQuery plugin for creating image sliders of any kind. Plugin converts any list of images into a slideshow, it can display captions with each slide, include links and there are multiple transition effects.