Mo.Mesfer
Mo.Mesfer

Reputation: 77

JavaScript: get the sender element

I have this code:

var x = document.getElementsByClassName("hex");
     
for(var i = 0; i < x.length; i++)
{
    x[i].addEventListener("click", myFunction);
}

To attach onclick dynamically. My question is myFunction how to get the clicked element?

Upvotes: 7

Views: 17172

Answers (1)

yihangho
yihangho

Reputation: 2225

Let myFunction take in an argument (call it event). event.target is then the clicked element:

function myFunction(event) {
    var clickedElement = event.target;
    // Do important stuff with clickedElement.
}

Upvotes: 13

Related Questions