JSFiddle - React, Tailwind, and code Playground
CSS
.button {
width: 20%;
height: 20vh;
background-color: white;
}
JavaScript
function addButtons(){
const a = document.createElement("button")
a.innerHTML = "button1"
a.className = "button"
a.id = "button-1"
document.body.appendChild(a)
//works only when done this way
setTimeout(()=>{
document.getElementById("button-1").onclick = ()=>
{console.log(1)}
})
document.body.innerHTML +=
"<button id='button2' class='button'>button2</button>"
//works when button4 is absent
document.getElementById("button2").onclick = ()=>{console.log(2)}
}
function addButtons1(){
const a = document.createElement("button")
a.innerHTML = "button3"
a.className = "button"
//works when button4 is absent
a.addEventListener("click", ()=>{console.log(3)})
document.body.appendChild(a)
document.body.innerHTML +=
"<button id='button4' class='button'>button4</button>"
//works
document.getElementById("button4").onclick = ()=>{console.log(4)}
}
function addButtons2(){
const a = document.createElement("button")
a.innerHTML = "button5"
a.className = "button"
//works
a.onclick = ()=>{console.log(5)}
document.body.appendChild(a)
const b = document.createElement("button")
b.innerHTML = "button6"
b.className = "button"
//works
b.onclick = ()=>{console.log(6)}
document.body.appendChild(b)
}
addButtons()
addButtons1()
addButtons2()