myDiv = document.getElementById('results');
div = myDiv.getElementsByTagName('div');
for (var i = 0; i < div.length; i++) {
var division;
division = div[i];
// console.log(div[i]);
division.addEventListener('mouseover', function () {
division.style.fontWeight = "bold";
division.style.background = "rgba(0, 7, 255, 0.29)";
}, false);
division.addEventListener('mouseout', function () {
division.style.fontWeight = "";
division.style.background = "";
}, false);
Here is the html code :
<div id="results">
<div>Resulat 1</div>
<div>Resulat 2</div>
</div>
My script which bold and put a background on some text is when the mouse pointer is over it working only for the second element.. ( <div>Resulat 2</div>)
Can someone tell me why because everything I did is right for me, even though I’m a JS beginner.
What is
divisionin yourfunction()? It is the same as thedivisionyou change in every iteration atdivision = div[i];. After your for-loop has finisheddivisionisdiv[1]. This is why you only change the second div.You could use a closure to tackle this problem, or use access the associated object with
this:However, your desired effect can be easily achieved with CSS: