I want to iterate through a class and display the corresponding text when I hover over each element.
HTML
<div class="box red"></div>
<div class="box green"></div>
<div class="box red"></div>
<div class="info">
Hi
</div>
<div class="info">
Hello
</div>
<div class="info">
Hey
</div>
CSS
.box {
width:100px;
height:100px;
border-radius: 10px;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
.info {
display: none;
}
Javascript
var box = document.getElementsByClassName("box");
for (var i = 0; i < box.length; i++) {
box[i].onmouseover = function(){
var info = document.getElementsByClassName("info");
info[i].style.display= "block";
}
}
for (var i = 0; i < box.length; i++) {
box[i].onmouseout = function(){
var info = document.getElementsByClassName("info");
info[i].style.display= "block";
}
}
I get an error
Uncaught TypeError: Cannot read property 'style' of undefined"
It works if I set each <div>
with an <id>
then repeat my code over and over again. Why is it not working if I iterate?