I've noticed a funny behavior and was wondering if anybody could shed some light on the reason.
It breaks down like this:
- I've added a
divand abuttonusing Javascript's `appendChild'. - I add an
onclickhandler to the button, works fine - I add-assign the
innerHTMLof thedivto add some more content - Button
onclickstops working altogether
Here's a sample script:
var D = document.createElement("DIV"), B = document.createElement("BUTTON");
B.innerHTML = "Is it true?";
document.body.appendChild(D);
D.appendChild(B);
B.onclick = function() { alert("Elvis Lives!"); }
At this point, it works fine. Then, add this line:...
D.innerHTML += "What about Tupac?";
...and the button breaks. So, I'm just using appendChild for all elements now.
But -
- Why is this happening ("seems like it should work :) ")
- Is there a fix (besides appending all my extra elements)?