Categories: JavaScriptjQuery

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.

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.

View Comments

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

Recent Posts

Free GG Mug Mockup

GG Mug Mockup designed for logo branding of companies and brands.

6 years ago

Lovtony Font Duo – Modern Sans Serif

A great font/script for creating beautiful logos, posters, wedding invitations, blog posts, social media, and…

6 years ago

Free Men T-Shirt Mockup

Realistic T-Shirt Mockup PSD which you can use freely to showcase your apparel design.

6 years ago

Classic Coffee Mug Mock-up Free PSD

Classic coffee mug Mock-up Free PSD. Free mug mockup PSD to showcase your branding design…

6 years ago

Juliette – Stylish Handwritten Signature Font

Juliette - Stylish Handwritten Signature Font

6 years ago

XXII Aven Sans Serif Font Family

XXII Aven Font Family - a new modern all-caps sans serif font with versatility in creativity.

6 years ago