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?
This question is related to
javascript
jquery
if-statement
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.
You can use the visible selector:
Assuming you are trying to find if a div exists
$('div').length ? alert('div found') : alert('Div not found')
I use this:
if ($('.div1').size() || $('.div2').size()) {
console.log('ok');
}
Mostly, I prefer to use this syntax :
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.
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.
Source: Stackoverflow.com