jQuery - Does a DOM element exist or not

Goal:
How to find out if a DOM element exists using jQuery:

Solution:
There are many ways to skim a cat, but I find the easiest way is to do:

$("#theItem")[0]

So you can do an IF-THEN-ELSE:

if(!$("#theItem"))[0]{
    //it is undefined and does not exist
}

Print | posted @ Monday, April 30, 2012 5:39 PM

Comments on this entry:

Gravatar # re: jQuery - Does a DOM element exist or not
by Zach at 4/30/2012 11:29 PM

Your missing the ")" in the if statement.
Gravatar # re: jQuery - Does a DOM element exist or not
by Arun Mahendrakar at 5/1/2012 11:11 PM

Please see the comparison on jsperf.com

http://jsperf.com/element-exists

.length seems to be a little faster!
Post A Comment
Title:
Name:
Email:
Comment:
Verification: