November 12, 2011

jQuery: DOM Element Existence

I probably have asked Google a thousand times how to check whether a DOM element exists. jQuery will always return a jQuery object when asked, so this won’t work:

if ($("#element")) {
  /* do something */
}

The move here is to check the length of that object, which is going to be zero if the object doesn’t exist.

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

Or, even easier:

if ($("#element").length) {
  /* do something */
}