Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different methods (listed below)
$(document).ready(function() { if ($('#DivID').length){ alert('Found with Length'); } if ($('#DivID').length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') != null ) { alert('Found with Not Null'); } });
Which one of the 3 is the correct way to check if the div exists?
EDIT: It's a pitty to see that people do not want to learn what is the better approach from the three different methods. This question is not actually on "How to check if a div exists" but it's about which method is better, and, if someone could explain, why it it better?
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.
$(document). ready(function() { if ($('#DivID'). length){ alert('Found with Length'); } if ($('#DivID'). length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') !=
The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With