cuando inyecto algún código, el onclick no funciona aquí es el código que uso.
document.getElementById('headbar').onclick = function() { var list_div_preleva = document.getElementsByClassName('preleva_dati').length; var list = document.getElementsByClassName('box_commenti'); for(var i = list_div_preleva; i < list.length; i++) { var parentDiv = list[i].parentNode.id; var id_post = document.getElementById(parentDiv); var creaelementodiv = document.createElement("button"); creaelementodiv.className = "preleva_dati"; creaelementodiv.setAttribute("id", "blocco_dati"); creaelementodiv.innerHTML = "<li>preleva il post</li>"; id_post.appendChild(creaelementodiv); } }; <div id="headbar">div</div>cuando el código está dentro, onclick no funciona
<!-- begin snippet: js hide: false console: true babel: false --> document.getElementById('blocco_dati').onclick = function() { alert(11); }; document.getElementById('headbar').onclick = function() { var id_post = document.getElementById("headbar2"); var creaelementodiv = document.createElement("button"); creaelementodiv.className = "preleva_dati"; creaelementodiv.setAttribute("id", "blocco_dati"); creaelementodiv.innerHTML = "preleva il post"; creaelementodiv.setAttribute("onclick", "doSomething();"); id_post.appendChild(creaelementodiv); }; function doSomething() { alert(11); }; <div id="headbar">div</div> <div id="headbar2"></div>Puede establecer un atributo más mientras inyecta el elemento
por ejemplo:
creaelementodiv.setAttribute("onclick", "doSomething();");y luego puedes llamar a esa función como
function doSomething() { alert(11); };