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?

Answers:

Answer

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

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

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/

Answer

You can use the visible selector:

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

Answer

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.

Answer
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.

Answer

I use this:

if ($('.div1').size() || $('.div2').size()) {
    console.log('ok');
}
Answer

Mostly, I prefer to use this syntax :

if ($('#MyId')!= null) {
    // dostuff
}

Even if this code is not commented, the functionality is obvious.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.