in template strings (like ...${btn}...
) the replacement values are converted to their String representation ([object HTMLButtonElement]
here).
inner-/outerHTML
are considered unsafe and slow. There are several alternatives to inject html into an existing element. In the snippet append
is used. For handling the button, by the way, the snippet uses event delegation.
See also ...
document.addEventListener(`click`, handle);
// ↓ create a button with class .doclickme
const btn = Object.assign(document.createElement('button'), {className: `doclickme` });
// ↓ append text to the button
btn.append(document.createTextNode(`do click me!`));
// ↓ append the button to the div
document.querySelector(`div`).append(btn);
// ↓ the document wide handling function
function handle(evt) {
if ( evt.target.closest(`.doclickme`) ) {
console.clear();
return console.log(`Hi. I am indeed added dynamically`);
}
}
<div>
Please give me a button!
</div>