Click to See Complete Forum and Search --> : Looping through IDs and getting a "Null Or Not An Object" error


britsky
04-20-2006, 08:10 PM
We've got a set of span tags, and only 1 is visible at a time. When we click the "next" link, our switchForward function is supposed to loop through all the span tags to make them hidden, then show the 1 appropriate span tag.

We're doing something wrong with the
document.getElementById(i).className = "hiddenObject"
command.

When I try it with hard-coded ID's like:
document.getElementById('0').className = "hiddenObject"
it works just fine. However, I can't do that since the number of <span> tags is based on a database query.


<script language="javascript">
function switchFoward(index, total)
{
var i=1;
for (i=1;i<=total;i++)
{
// hides all the span tags
document.getElementById(i).className = "hiddenObject";
}
// reveals the 1 appropriate span tag
document.getElementById(index).className = "revealedObject";
}

</script>
<span id="0" class="revealedObject">
blah blah blah
<a onmouseover="this.style.cursor='pointer'" onclick="switchFoward('1', '13');"> Next </a>
</span>
<span id="1" class="hiddenObject">
blah blah blah
<a onmouseover="this.style.cursor='pointer'" onclick="switchFoward('2', '13');"> Next </a>
</span>
.
.
.
<span id="13" class="hiddenObject">
blah blah blah
</span>


Thanks in advance for your help! God bless!
-Jeff

phpnovice
04-20-2006, 10:33 PM
ID's are supposed to start with an alphabetic character.

TheBearMay
04-21-2006, 06:57 AM
May want to consider:

document.getElementsByTagName("span")[i].className

or

document.getElementById("'"+i+"'").className

instead.

Orc Scorcher
04-21-2006, 07:08 AM
Either check that getElementById did not return null or wrap the statement in a try-catch block. The latter method is not compatible with IE 5.0 or older browsers, don't know if you care about that.