jQuery - how to check if an element exists?

JavascriptJqueryIf Statement

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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 - Javascript

You can use the visible selector:

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

Solution 4 - Javascript

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 - Javascript

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.

Solution 6 - Javascript

I use this:

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

Solution 7 - Javascript

Mostly, I prefer to use this syntax :

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionA-OKView Question on Stackoverflow
Solution 1 - JavascriptBjarki HeiðarView Answer on Stackoverflow
Solution 2 - JavascriptHusseinView Answer on Stackoverflow
Solution 3 - JavascriptSteve WellensView Answer on Stackoverflow
Solution 4 - JavascriptHoganView Answer on Stackoverflow
Solution 5 - Javascriptdeveloper2001View Answer on Stackoverflow
Solution 6 - Javascriptcn007bView Answer on Stackoverflow
Solution 7 - JavascriptImagerie NumériqueView Answer on Stackoverflow