I'm using the .length
method in a conditional statement that polls the page for the presence of an externally-loaded object (I can't style it with jQuery until it exists):
function hackyFunction() { if($('#someObject').length<1) { setTimeout(hackyFunction,50) } else { $('#someObject').someMethod() }}
Is length
the best way to do this?
If you are simply looking for a specific element you can just use document.getElementById
function hackyFunction() {
if (document.getElementById("someObject")) {
// Exist
} else {
// Doesn't exist
}
}
Yes you should use .length
. You cannot use if ($('#someObject')) ...
because the jQuery selectors return a jQuery object, and any object is truthy in JavaScript.
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