Manipulating innerHTML removes the event handler of a child element? [duplicate]

I have this very simple demo:

function foo() {
    alert('Works!');
}

var inp = document.createElement('input');
inp.onblur = foo;
document.body.appendChild(inp);

See here: http://jsfiddle.net/A7aPA/

As you can see, this works. (Click on the input, then click somewhere else and an alert will pop up.)

However, if I add this line to the JavaScript code:

document.body.innerHTML += '<br>'; 

then the blur handler stops working (and no error is thrown btw).

See here: http://jsfiddle.net/A7aPA/1/

Why is that?


Yes, when you do:

document.body.innerHTML += '<br>'; 

You're really doing:

document.body.innerHTML = (document.body.innerHTML + '<br>'); 

So you're completely destroying and recreating all the content.


Modifying innerHTML causes the content to be re-parsed and DOM nodes to be recreated, losing the handlers you have attached. Appending elements as in the first example doesn't cause that behavior, so no re-parsing has to occur, since you are modify the DOM tree explicitly.

Another good way to handle this is to use insertAdjacentHTML(). For example:

document.body.insertAdjacentHTML('beforeend', '<br>')