Forum Moderators: open

Message Too Old, No Replies

Set visibility for all DIVs belonging to a class

How to cycle through a set of elements belonging to the same class?

         

McAldo

5:06 pm on Sep 27, 2010 (gmt 0)

10+ Year Member



Hi,

I was wondering if anybody could suggest a code to change visibility for all DIVs belonging to the same class.

For instance, if we had:

<DIV class="Main" id="MickeyMouse">
Some Content
</DIV>

<DIV class="Main" id="DonaldDuck">
Some Other Content
</DIV>

<DIV class="OtherClassName" id="DonaldDuck">
Yet further content
</DIV>

I would like to toggle the visibility of the two layers belonging to the class 'Main', ideally with a cross-browser code.

Any idea how this might be accomplished?
I tried something like:

function HideClass(ClassName) {

var myParentClass=document.getElementById(ClassName);
for (i=0; i<myParentClass.childNodes.length; i++){
myParentClass.childNodes[i].style.visibility = "hidden";
}



triggered by :
<li><a href="javascript:HideClass('main')">Hide all!</a></li>


but it doesn't seem to work.
My knowledge of the DOM is very limited, I am afraid.

Thank you very much,
Aldo

MichaelBluejay

3:36 am on Sep 28, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here you go. It's pretty easy, you just collect all the DIV's into an array, then loop through them and hide any DIV whose class name matches.

<script type=text/javascript> 
function hidey() {
divs=document.getElementsByTagName("DIV");
for (theDiv in divs) {
if (divs[theDiv].className=="Main") divs[theDiv].style.visibility="hidden";
}
}
</script>

<div class="Main">Main 1</div>
<div class="Main">Main 2</div>
<div class="Main">Main 3</div>
<div class="Other">Other</div>

<p><a href="javascript:hidey()">Hidey Hidey Hidey Ho</a>