if ($('#elementId')) { //Do something if element exists } else { //Do something else if element doesn't exist }However, when I used it against a jQuery variable that is supposed to hold HTML elements that met certain selector, it didn't work correctly. The problem is there is no element in the variable but it evaluates to true. This is due to jQuery returns Object [ ] which is empty array of object and the array itself exists thus the expression returns true.
Some suggestions I found online are:
- Use length properties, so it becomes if ($('#elementId').length){}
- In jQuery version 1.4 or above, you can use $.isEmptyObject() function
Another way that works for me is to get its first element:
if ($('#elementId')[0]){}
The one that I often used lately is:
var elements;
if (elements && elements.length) { }