JQuery - how to check if an element exists?

I know you can check for width() or height() , but what if the element's display property is set to none? What else needs to be checked to make sure the item exists?

+48
javascript jquery if-statement
Mar 13 2018-11-11T00:
source share
7 answers

You can use length to find out if your selector matches anything.

 if ($('#MyId').length) { // do your stuff } 
+145
Mar 13 '11 at 23:14
source share

Assuming you are trying to find if a div exists

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

Check out the working example http://jsfiddle.net/Qr86J/1/

+15
Mar 13 '11 at 23:26
source share

You can use the visible selector:

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

+2
Mar 13 '11 at 10:59 a.m.
source share

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

Does it help? Not sure without additional information.

+2
Mar 13 '11 at 10:59 a.m.
source share
 if ($("#MyId").length) { ... write some code here ...} 

This automatically checks for the presence of the element and returns true if the element exists.

+2
May 04 '14 at 19:08
source share

I use this:

 if ($('.div1').size() || $('.div2').size()) { console.log('ok'); } 
0
Jan 15 '15 at 7:26
source share

Basically, I prefer to use this syntax:

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

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

-3
Oct. 27 '15 at 11:21
source share



All Articles