1

I'm trying to use getElementsByClassName, to hide HTML elements with onclick function. I'm using a for loop to iterate the array created by getElementsByClassName.

But this way I'm getting a: Uncaught TypeError: Cannot read property 'style' of undefined at HTMLDivElement.circles..onclick

Any ideas? Thanks a lot in advance.

<div class="circle" id="red-circle"></div>
<div class="circle" id="blue-circle"></div>
<div class="circle" id="yellow-circle"></div>

===============================================

const circles = document.getElementsByClassName("circle")


    for(var i = 0; i < circles.length; i++) {
        circles[i].onclick = () => {
            circles[i].style.display = "none"

        }
    }

1 Answers1

2

You should change your arrow function:

for(var i = 0; i < circles.length; i++) {

        circles[i].onclick = (e) => {
            e.currentTarget.style.display = "none"
        }
}

e refers to mouse event, and currentTarget is the clicked element.

Saman Gholami
  • 3,416
  • 7
  • 30
  • 71