jQuery - how to check if an element exists? jQuery - how to check if an element exists? javascript javascript

jQuery - how to check if an element exists?


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

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


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/