[ACCEPTED]-jQuery - how to check if an element exists?-if-statement

Accepted answer
Score: 153

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

if ($('#MyId').length) {
    // do your stuff
Score: 15

Assuming you are trying to find if a div 1 exists

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

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

Score: 2

You can use the visible selector:



Score: 2

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

Does 1 this help? Not sure without more info.

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

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

Score: 0

I use this:

if ($('.div1').size() || $('.div2').size()) {


More Related questions