Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
Is there any way to see if an object exists?
After the getElementById
call, codeName
is either a DOM Element or null. You can use an alert to see which:
alert(codeName);
So if (codename != null)
should work.
Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger.
Try:
var codeName = document.getElementById(code[i]) || null;
if (codeName) {/* action when codeName != null */}
if you want to be sure codeName is an Object:
if (codeName && codeName instanceof Object) {
/* action when codeName != null and Object */
}
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