JavaScript Event Delegation, and event.target vs. event.currentTarget

<body>
<div id="container">
<ul id="list">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
..................................
<li><a href="#">Item 1000</a></li>
</ul>
</div>
</body>
document.addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "A") {
console.log("List item ", e.target.textContent, " was clicked!");
}
});
// When we click the 2nd item, the page prints out:"List item Item 2 was clicked!"

target vs. currentTarget

Since we already talked about the event.target property, there is another property called event.currentTarget in JavaScript event. It can be very confused by just reading about them on JavaScript documentation.

<a> → <li> → <ul> → <div> → <body>
document.addEventListener(“click”, function(e) {
if(e.target && e.target.nodeName == “A”) {
console.log(“List item “, e.target.textContent, “ was clicked!”); // "List item Item 2 was clicked!"
}
console.log(e.currentTarget); // #document
});
document.getElementById(“list”).addEventListener(“click”, function(e) {
console.log(e.currentTarget); //<ul><li>...</li><ul>
console.log(e.target); //<a href="#">Item 2</a>
);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store