I try to get some elements from html, that may or may not exist. Now if I just try
//previous code
document.getElementById("MyElement1").checked = false;
document.getElementById("MyElement2").checked = false;
...
//rest of the code
then the rest of the code won't get executed if one of the elements doesn't exist.
I would just do
try {
document.getElementById("MyElement1").checked = false;
document.getElementById("MyElement2").checked = false;
...
} catch (e) {
console.log(e);
}
but it is said that you should never use a try...catch for non serious errors.
Is there a more elegant way that makes javascript ignore this line of code if one of these elements doesn't exist?
PS: If one of these elements doesn't exist, the following ones won't either. So if MyElement1
exists, but MyElement2
doesn't, then MyElement3
, MyElement4
etc won't exist either.
Also I try to avoid large chunks of code like using an if for each one of these elements