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
div
and abutton
using Javascript's `appendChild'. - I add an
onclick
handler to the button, works fine - I add-assign the
innerHTML
of thediv
to add some more content - Button
onclick
stops 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)?