Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 464
MedoMe Avatar asked Sep 16 '16 16:09

MedoMe


1 Answers

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.
}
like image 56
yihangho Avatar answered Oct 20 '22 09:10

yihangho