PDA

View Full Version : Resolved Element is null?



bluewalrus
11-18-2010, 05:51 AM
Is this the incorrect syntax? I'm trying to find which in a series of 5 IDs is not set.


for (i=1;i<=6;i++) {
if (document.getElementById('inactive' + i) === null) {
alert("it is" +i);
}
}

traq
11-19-2010, 01:32 AM
you mean "inactive1", "inactive2", etc.? Just "if" works:
for (i=1; i<6; i++) {
if(!document.getElementById('inactive' + i){ alert('it is ' + i); }
}

jscheuer1
11-19-2010, 09:32 AM
You should declare the variable i. In this context ++i (pre-increment) is more efficient than i++ (post-increment). Also, and Adrian corrects this in his code but doesn't mention it, there is a difference between +i and + i. The former means "positive i" and is roughly equivalent to parseFloat(i) or 1 * i. In the context of the code, this would be a syntax error. The latter means "plus i" (in this context "concat the string 'it is' and the value of i). So that's the big no no in the original code. In the alert I think you want a space after "is". If we don't want a bunch of alerts in cases where - say only inactive1 exists, we should return from the function. So we could then have:


for (var i = 1; i <= 6; ++i) {
if (document.getElementById('inactive' + i) === null) {
alert("it is " + i);
return;
}
}

But, as Adrian points out, such a strict test of the element isn't required. What he doesn't mention is that it might fail in some cases (though I'm not certain of that, if it doesn't it's preferred for efficiency's sake). In any case his solution works:


for (var i = 1; i <= 6; ++i) {
if (!document.getElementById('inactive' + i)){
alert("it is " + i);
return;
}
}

Note: Looking back over this I realized that this code might not be in a function, or even if it is we might not want the function to return just because it 'finds' a missing element. If that's the case we can substitute break; for return; - That way it will break out of the loop regardless of whether or not the loop is inside a function or not and continue processing after the closing brace of the for statement.

traq
11-19-2010, 03:09 PM
thanks John, javascript isn't my strong suit (I'm really just now starting to get comfortable) - what I offered was based solely on testing and finding out it works :D The things I "didn't mention," I didn't know. Thanks for expounding!

bluewalrus
11-22-2010, 12:16 AM
Yup that did it. Thanks.