javascript - dom searching for id returns an error - how to handle?
for (i=1; i<=4; i++) {
try {
timer = document.getElementById("timer"+i).parentNode.parentNode.parentNode.childNodes[1].childNodes[0].childNodes[0].className;
}
catch(e) {
FM_log("aguardaReforcos()", "ERRO - timer"+i);
}
...
I have to it this way with try becau开发者_Go百科se otherwise I get a crash when it doesn´t find document.getElementById("timer"+i).parentNode.parentNode.parentNode.childNodes[1].childNodes[0].childNodes[0].className
is there another way of preventing this type of crash?
You can use each of the properties in turn without causing a crash, but the code will of course contain a whole lot of tests:
var timer = document.getElementById("timer"+i);
if (timer) {
timer = timer.parentNode;
if (timer) {
timer = parentNode;
if (timer) {
// and so on...
}
}
}
精彩评论