jQuery - how to check if an element exists?
JavascriptJqueryIf StatementJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}
Solution 2 - Javascript
Assuming you are trying to find if a div exists
$('div').length ? alert('div found') : alert('Div not found')
http://jsfiddle.net/Qr86J/1/
Check working example atSolution 3 - Javascript
You can use the visible selector:
Solution 4 - Javascript
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.
Solution 5 - Javascript
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.
Solution 6 - Javascript
I use this:
if ($('.div1').size() || $('.div2').size()) {
console.log('ok');
}
Solution 7 - Javascript
Mostly, I prefer to use this syntax :
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.