Search code examples
javascripthtmldominnerhtml

What is wrong with the next sibling of the textarea?


When this script is inserted into HTML document, it causes the strange behaviour. The shown textarea element losts its value after the <br> tag insertion (I've tested it in the Chrome 42):

var text = document.createElement("textarea");
document.body.appendChild(text);
text.value = "text";
alert("value presents");
document.body.innerHTML += "<br>"; //(*)
alert("value absents");

What is the reason for this?


Solution

  • Change this:

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

    to this:

    document.body.appendChild(document.createElement("br"));
    

    This will append a single new element to the DOM rather that replace the entire contents of your DOM with all new elements.

    When you do this:

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

    it is the equivalent of this:

    var str = document.body.innerHTML;
    str += "<br>";
    document.body.innerHTML = str;
    

    So, you are turning the entire body DOM into an HTML string, adding one thing onto the end of the string, then replacing the entire body DOM with a new piece of HTML which will create all new elements.

    Besides the inefficiency of doing it this way, it also replaces all the DOM elements with different DOM elements so any DOM references or event handlers are now broken and any dynamic changes you made to DOM elements that aren't reflected in the HTML will be lost.