Change Class of all images in div

This is probably really simple but I cant seem to figure it out.


<div id="imgcontainer" class="imgcontainer">
<img onclick="makeActive(1)" class="active" src="images/demo_01.gif" alt="testimonial" />
<img onclick="makeActive(2)" src="images/demo_02.gif" alt="testimonial" />
<img onclick="makeActive(3)" src="images/demo_03.gif" alt="testimonial" />
<img onclick="makeActive(4)" src="images/demo_04.gif" alt="testimonial" />
<img onclick="makeActive(5)" src="images/demo_05.gif" alt="testimonial" />
<img onclick="makeActive(6)" src="images/demo_06.gif" alt="testimonial" />
</div>
<div class="show" id="imgdesc1">text1</div>
<div class="hidden" id="imgdesc2">text2</div>
<div class="hidden" id="imgdesc3">text3</div>
<div class="hidden" id="imgdesc4">text4</div>
<div class="hidden" id="imgdesc5">text5</div>
<div class="hidden" id="imgdesc6">text6</div>


function makeActive(num){
//clear all image classes in imgcontainer div
//apply class active to clicked image (this.className = 'active';)
//show corresponding imgdesc div
}

When an image is clicked it should:

  1. clear the classes of all of the images
  2. assign the clicked image a class of “active”
  3. I then want to show a corresponding text (which would be in the same function.

Thanks for helping!

var images = document.getElementById('imgcontainer').getElementsByTagName('img');
for(var i=0; i<images.length; i++)
{
  var active = (i == num - 1);
  if(active)
  {
     images[i].className = 'active';
     document.getElementById('imgdesc' + (i + 1)).className = 'show';
  }
  if(!active && images[i].className == 'active')
  {
     images[i].className = '';
     document.getElementById('imgdesc' + (i + 1)).className = 'hidden';
  }
}

Works like a charm. You’re the man.

You could get away without doing that extra check - the changing of the classnames wouldn’t be that big of a hit, and it would ensure it catches everything…


var images = document.getElementById('imgcontainer').getElementsByTagName('img');
for(var i=0; i<images.length; i++) {
  var active = (i == num - 1);
  if(active) {
     images[i].className = 'active';
     document.getElementById('imgdesc' + (i + 1)).className = 'show';
  } else {
     images[i].className = '';
     document.getElementById('imgdesc' + (i + 1)).className = 'hidden';
  }
}

Or even


var images = document.getElementById('imgcontainer').getElementsByTagName('img');
for(var i=0; i<images.length; i++) {
    images[i].className = (i == num - 1) ? 'active' : '';
    document.getElementById('imgdesc' + (i + 1)).className = (i == num - 1) ? 'show' : 'hidden;
}

Sweet deal Dave. Both of those work as well.

Thanks both!