How to check if an element exists in jQuery

if ( $("#mydiv").length ){
  // do something here
}

Briefer again…

if ( $("#mydiv")[0] ){
  // do something here
}

via http://aaronrussell.co.uk/legacy/check-if-an-element-exists-using-jquery/

2 thoughts on “How to check if an element exists in jQuery

  1. I personally find this to be the best:

    if( $('#mydiv').length ) { /* do stuff */ }

    length is better since it returns an

    int

    (0 if no elements found). The other approach returns undefined if no elements found.

    1. Sure, length is probably best.

      But the second method works. Even when it returns undefined, it fails the conditional statement.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s