Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setup an "if object exists" condition?

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?

like image 306
MrM Avatar asked Nov 26 '22 17:11

MrM


2 Answers

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.

like image 177
Jason Orendorff Avatar answered Feb 04 '23 02:02

Jason Orendorff


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 */
}
like image 44
KooiInc Avatar answered Feb 04 '23 01:02

KooiInc