20-04-2008

jQuery jQuery check if dom element exists

The jQuery object $("#myid") always returns something - a jQuery object. To check if it actually represents an excisting DOM element on the page you can use the following:

if ( $("#myid").length > 0 ) {
//do something
}

Comments:

11 comments.
Your comment:

»
daniel 22/04/2010, 3:37 pm
perfect, exactly what I needed, thanks!
Silvio Sá 10/05/2010, 7:16 pm
Thank you. Your hint was useful 2 year after you've posted. I would never think in checking the object's length.
Binod Shukla 04/10/2010, 7:22 am
Very nice trick ! Thumbs UP !!!!
PJ 18/10/2010, 4:44 pm
Thanks for the tip
marik_v 22/11/2010, 3:21 pm
excelent
attila 11/03/2011, 11:35 am
dzsííír
Eagle 16/04/2011, 8:36 pm
Thanks a lot for the quick tip!
Jainish 27/04/2011, 1:54 pm
Thanks..
Nicooprat 03/05/2011, 3:55 pm
You should use .length() ( or .size() ) method instead of .length attribute because it's a jQuery method.

I had some issue using .length attribute, but I can't remember which one !
Besik 10/06/2011, 1:29 pm
Very nice! small piece of script which solves big problems! now using at http://www.livepage.info
nay 26/11/2011, 4:42 am
exactly what I needed. Thanks

 

[x]