Division By Zero

How to tell if an HTML element exists using JQuery

Up until now I had assumed that if i need to detect the presence of (or lack of) an element on a webpage I could simply use the following:

if($('.elementClass')) { //some code here }

but I found today that this doesn’t actually work. Whether the element exists or not you will still get a JQuery object returned, which of course equates to TRUE.

So I decided to RTFM and found that the JQuery object has an attribute, ‘length’, which returns the number of elements. So of course it will be zero if the element wasn’t found. So my code, which runs if the element is present now reads:

if($('.elementClass').length != 0) { //some code here }

Simple eh? Of course you can also say == 0 if you want some code to run if an element isn’t found.

Spread the word

If you like what you've read, help spread the word on Twitter, Digg, or any of your favourite social sites. Knowledge is power.

About the author

Jonathan Phillips is the founder and main author here on Division by Zero. A PHP developer by trade, Jonathan spends his days building and marketing websites and the rest of the time coming up with ideas for websites and businesses he hasn't got time to implement.

Leave a comment

* denotes a required field

Don't worry, your email address etc. is safe, we won't share it with anyone.

Copyright © 2009 - 2010 Division By Zero - Credits