jQuery - how to check if an element exists?

I know that you can test for width() or height() but what if the element's display property is set to none? What other value is there to check to make sure the element exists?


Solution 1:

You can use length to see if your selector matched anything.

if ($('#MyId').length) {
    // do your stuff
}

Solution 2:

Assuming you are trying to find if a div exists

$('div').length ? alert('div found') : alert('Div not found')

Check working example at http://jsfiddle.net/Qr86J/1/

Solution 3:

You can use the visible selector:

http://api.jquery.com/visible-selector/

Solution 4:

jQuery should be able to find even hidden elements. It also has the :visible and :hidden selectors to find both visible and hidden elements.

Does this help? Not sure without more info.

Solution 5:

if ($("#MyId").length) { ... write some code here ...}

This from will automatically check for the presence of the element and will return true if an element exists.