Unfortunately, assignment to innerHTML
causes the destruction of all child elements, even if you’re trying to append. If you want to preserve child nodes (and their event handlers), you’ll need to use DOM functions:
function start() { var myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; var mydiv = document.getElementById("mydiv"); mydiv.appendChild(document.createTextNode("bar")); }
Edit: Bob’s solution, from the comments. Post your answer, Bob! Get credit for it. 🙂
function start() { var myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; var mydiv = document.getElementById("mydiv"); var newcontent = document.createElement('div'); newcontent.innerHTML = "bar"; while (newcontent.firstChild) { mydiv.appendChild(newcontent.firstChild); } }