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?
7 Answers
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
contactmatt
Ehhh, it'd be clearer to use .length > 0 , rather than the implicit "truthy" check.
Mostly, I prefer to use this syntax :
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.
2 Comments
Alsan
This will always retun true.
Imagerie Numérique
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...
display: none. The distinction is particularly important for form controls; they'll be submitted whether they're visible or not.