What you’re trying to do is called event delegation, however, you’re trying to access the clicked element via this
. This might work in jQuery, but in regular JavaScript events (e.g. by binding to the onclick
property or by using addEventListener
) this
refers to the object you’re binding the event to, i.e. in code like this, this
always refers to <body>
:
document.body.onclick = function(ev) {
console.log("onclick variant — `this` is", this);
};
document.body.addEventListener("click", function(ev) {
console.log("addEventListener variant — `this` is", this);
});
<div>Click me to see what <code>this</code> refers to.</div>
To see which element actually has been clicked, in a nutshell, you need ev.target
:
document.body.onclick = function(ev) {
console.log("onclick variant — `ev.target` is", ev.target);
};
document.body.addEventListener("click", function(ev) {
console.log("addEventListener variant — `ev.target` is", ev.target);
});
<div>Click me to see what <code>this</code> refers to.</div>
Use addEventListener
, since this is more modern and allows binding more than one event listener and provide more control over event propagation.