52

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?

cn007b
  • 16,596
  • 7
  • 59
  • 74
A-OK
  • 3,184
  • 10
  • 34
  • 42
  • "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
  • 2
    possible 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 Answers7

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

You can use the visible selector:

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

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
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.