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?
Asked
Active
Viewed 1.7e+01k times
52
-
"exists" isn't quite the same as "displayed" – David Tang Mar 13 '11 at 23:05
-
possible duplicate of [Check if element exists](http://stackoverflow.com/questions/4795928/check-if-element-exists) – ifaour Mar 13 '11 at 23:07
-
For reference, an element "exists" even when it's set to `display: none`. The distinction is particularly important for form controls; they'll be submitted whether they're visible or not. – cHao Mar 13 '11 at 23:08
-
sorry, I was a super dumbass, I mixed up width() and length thinking they're the same. width() returns 0 or false (I don't know) when dislpay is none, length always works. – A-OK Mar 14 '11 at 00:01
-
2possible duplicate of [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – SpYk3HH Oct 03 '13 at 14:17
-
[***¡SEE THIS ANSWER!***](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery#answer-13313296) – SpYk3HH Oct 03 '13 at 14:18
7 Answers
153
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}

Subin Chalil
- 3,531
- 2
- 24
- 38

Bjarki Heiðar
- 3,117
- 6
- 27
- 40
-
26You don't need `> 0` as shown in my example below. `$('#MyId').length` alone will do it. – Hussein Mar 14 '11 at 00:01
15
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/

Hussein
- 42,480
- 25
- 113
- 143
-
Ehhh, it'd be clearer to use .length > 0 , rather than the implicit "truthy" check. – contactmatt Nov 06 '15 at 06:22
2
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.

Sebastian
- 6,293
- 6
- 34
- 47

developer2001
- 33
- 6
2
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.

Hogan
- 69,564
- 10
- 76
- 117
0
I use this:
if ($('.div1').size() || $('.div2').size()) {
console.log('ok');
}

cn007b
- 16,596
- 7
- 59
- 74
-3
Mostly, I prefer to use this syntax :
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.
-
-
Oh my... That's true... Thanks for the notice ! Hum it's weird I ain't got any problems with that... I think I gotta spend some time to correct this on my JS Dev... – Imagerie Numérique Jan 29 '16 at 06:40