From an outer function you can retrieve the element whos listener is bound to by using
Event.currentTarget
function click_function(evt) {
console.log(evt.currentTarget.id);
}
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#click").addEventListener("click", () => {
console.log("Clicked");
const btn = document.createElement('button');
btn.textContent = "Button"
btn.id = 'button';
btn.addEventListener("click", click_function);
document.querySelector('#newbutton').appendChild(btn);
});
});
<button id='click'>Click</button>
<div id='newbutton'></div>
PS: when creating new element on-the-fly, the onclick
is not such a bad practice - since it's its first bound event, but to assign events to already existent elements try always to use EventTarget.addEventListener - since oneelement can have multiple addEventListeners assigned, but only one on*
handler.
If you're going to create many elements in your app, here's another way with reusable Element function helpers:
const EL = (sel, EL) => (EL || document).querySelector(sel);
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
function click_function(id) {
console.log(id);
}
EL("#click").addEventListener("click", () => {
console.log("Clicked");
const btn = ELNew('button', {
id: "button",
type: "button", // Otherwise by default type is "submit"
textContent: "CLICK ME",
onclick() {
click_function(btn.id)
}
});
EL('#newbutton').append(btn);
});
<button id='click'>Click</button>
<div id='newbutton'></div>
or, instead of calling a handler that again calls a function...
onclick() {
click_function(btn.id)
}
or:
onclick: () => click_function(btn.id)
you could simply
onclick: click_function,
and than use Event.currentTarget
as in the first example - which provides you with more data than just getting the id
.