0

enter image description hereI was trying to highlight some elements on event mouseover using plain javascript. My code is below.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>

<body>
    <div id="container" class="container">
        <div class="class1">Class 1</div>
        <div class="class1">Class 2</div>
        <div class="class1">Class 3</div>
    </div>
    <script>
        var class1 = document.getElementsByClassName("class1");
        for (var i = 0; i < class1.length; i++) {

            class1[i].addEventListener('mouseover', function () {
                console.log(class1[i])
                this.setAttribute("style", "background-color:cyan;color:#ffffff")
                // class1[i].innerHTML += "working ";
            })
            class1[i].addEventListener('mouseleave', function () {
                console.log(class1[i])
                this.setAttribute("style", "background-color:#fff;color:#000")
                // class1[i].innerHTML += "working ";
            })
        }
    </script>
</body>

</html>

I noticed that class1[i] is undefined, but 'this' isn't. Why is it so?

Akil
  • 145
  • 4
  • It's because as of when the event handler runs, `i` is `class1.length`, so `class1[i]` is `undefined`. With `var`, there's a single `i` variable that the functions close over, and of course the value of that variable at the end of the loop is `class1.length`. If you used `let` in the `for` loop, the `for` loop would create a new `i` for each loop iteration and your code would work with `class[i]`. (In both cases, in modern environments, you'd be better off with `for (const element of class1) { /*...*/ }` and then use `element` instead of `class1`.) But... – T.J. Crowder Nov 17 '21 at 07:59
  • ...the advantage of using `this` (or `event.currentTarget`) in the handler is that instead of creating multiple event handler functions, you could create *one* of them and reuse it, because when it gets called, `this` is set to the element the handler was attached to (as is `event.currentTarget`). – T.J. Crowder Nov 17 '21 at 08:00

0 Answers0