Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Behavior of 'this' vs element itself in Javascript

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!