PDA

View Full Version : JavaScript - hide/show multiple divs


cangoalie
03-14-2008, 05:43 PM
Hi
I need to hide/show multiple divs with the clicking of a link. Basically, I want to have one link that allows the user to view all divs, then four links that select only one of my four "types" of divs (Meetings, Tables, Events, Other). The problem with this that I cannot solve is this: on the page I am building I will have more than one div of each type - for example, maybe three Meetings, two Tables, four Events and one Other. This prohibits me from using a JavaScript method using getElementById, as ids have to be individual. I have googled the hell out of this question but don't have any answers. Any help you can offer would be greatly appreciated.

mjlorbet
03-14-2008, 10:44 PM
var divList = document.getElementsByTagName("div");
function HideByTitle(titleList){
var titlesToHide = titleList.split(",");
for(var a = 0; a < divList.length; a++)
for(var b = 0; b < titlesToHide.length; b++)
if(divList[a].title == titlesToHide[b])
divList[a].style.display='none';
}
function ShowByTitle(titleList){
var titlesToShow = titleList.split(",");
for(var a = 0; a < divList.length; a++)
for(var b = 0; b < titlesToShow.length; b++)
if(divList[a].title == titlesToShow[b])
divList[a].style.display='block';
}



<a href="javascript:void(ShowByTitle('divtitle1,divtitle2,divtitle3'))">Show divs</a>
<a href="javascript:void(HideByTitle('divtitle1,divtitle2,divtitle3'))">Hide divs</a>

Assuming your divs have unique titles (or the same title for all elements in a group that you want to hide) you can also change title to any property unique to the group that you want to hide (for example className if you're using the same css class on a whole set of elements that should be hidden, shown at a given time), also, you can specify as many attributes as you want to hide or show elements by seperating them with commas in the show & hide parameters. hope this helps.