I am setting up a "bio" section on my site and I have 3 images of employees and 3 divs with each of the employees bios below. I want to hide all the bios by default and then display only the div associated with the image that is clicked and hide all other divs.
Currently it seems like it's not finding the elements because I am getting "undefined"
Here is my HTML so far:
<div onclick="showhide('bill');" class="bio_image"><div class="name">Bill Murray</div></div>
<div onclick="showhide('bill2');" class="bio_image"><div class="name">Bill Murray</div></div>
<div onclick="showhide('bill3');" class="bio_image"><div class="name">Bill Murray</div></div>
<div class="hide" id="bill">BILL</div>
<div class="hide" id="bill2">BILL2</div>
<div class="hide" id="bill3">BILL3</div>
And my Javascript:
function showhide(id){
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hide");
for(var div in divs) {
div.style.display = "none";
}
divid.style.display = "block";
}
return false;
}
JSFiddle
Any ideas? Thanks!
Use a regular
for
loop as afor in
loop will loop over the other properties of the NodeList and not just over the list of elementsJSFiddle
When using
for(var div in divs)
,div
is not the element. This notation is used when iterating JSON objects.You want to use this instead: