<script>
const test = el => alert(`Click: ${el.innerText}`);
const buildElement = (tagName, props = {}, attributes = {}) => {
const el = Object.assign(document.createElement(tagName), props);
for (let key in attributes) el.setAttribute(key, attributes[key]);
return el;
}
const btn1 = buildElement('button', {
className: 'my-button',
innerText: 'Best Button 1',
}, {
onclick: "test(this)"
});
const btn2 = buildElement('button', {
className: 'my-button',
innerText: 'Best Button 2',
}, {
onclick: "test(this)"
});
window.addEventListener('DOMContentLoaded', _ => {
document.body.insertAdjacentHTML('beforeend', btn1.outerHTML)
document.body.insertAdjacentHTML('beforeend', btn2.outerHTML)
})
</script>
Вриант вставки элементов с навешиванием событий на них