So in the past I’ve tried to come up with code so that when you click a link that “unhides” a div, that it closes the rest of them. Well today I was working on something where I needed that functionality and I thought I’d post it for all to use. I’m sure I’m not the first to come up with this, but here it is:
function show(id)
{
var divArray = document.getElementsByTagName(‘div’);
var div = document.getElementById(id);
for each (divItem in divArray)
{
if(divItem != div)
{
divItem.style.display=”none”;
}
else
{
divItem.style.display = “”;
}
}
}
So when you make a call to show() you pass the id of the div you would like to show. Show(‘one’); for instance would show the div where the id=”one” and would go through and hide the rest of the divs.
This code could be changed to use any type instead of just a div if desired.
EDIT: I found that in the array returned, the last element is the number of objects returned. If there were 3 divs, then it would be 3, if there were 4, then 4. You get the idea… One way to remove the problem of having the last item is putting an if statement around the if… else that already exists.
This could read: if(typeOf(divItem) == ‘object’)
Leave a Reply