53

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?

6
  • "exists" isn't quite the same as "displayed" Commented Mar 13, 2011 at 23:05
  • possible duplicate of Check if element exists Commented Mar 13, 2011 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. Commented Mar 13, 2011 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. Commented Mar 14, 2011 at 0:01
  • 2
    possible duplicate of Is there an "exists" function for jQuery? Commented Oct 3, 2013 at 14:17

7 Answers 7

154

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

if ($('#MyId').length) {
    // do your stuff
}
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need > 0 as shown in my example below. $('#MyId').length alone will do it.
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/

1 Comment

Ehhh, it'd be clearer to use .length > 0 , rather than the implicit "truthy" check.
2

You can use the visible selector:

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

Comments

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.

Comments

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.

Comments

0

I use this:

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

Comments

-3

Mostly, I prefer to use this syntax :

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

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

2 Comments

This will always retun true.
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.