Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  72] [ 6]  / answers: 1 / hits: 13059  / 10 Years ago, mon, march 17, 2014, 12:00:00

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!


More From » onclick

 Answers
4

Use a regular for loop as a for in loop will loop over the other properties of the NodeList and not just over the list of elements



function showhide(id){
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName(hide);
for(var i=0;i<divs.length;i++) {
divs[i].style.display = none;
}
divid.style.display = block;
}
return false;
}


JSFiddle


[#46783] Sunday, March 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
oliverkarle

Total Points: 96
Total Questions: 71
Total Answers: 105

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
;