Appending Child resets previous appended element value on JavaScript

后端 未结 1 831
梦如初夏
梦如初夏 2020-12-19 23:13

The situation is the following: I\'ve got a form with some input textboxes and a button that calls the add() function when clicked. This is the HTML code:

相关标签:
1条回答
  • 2020-12-19 23:52

    Try This

    See the working Demo Here

    You need to change line bar.innerHTML += "<br>"; to bar.appendChild(element3);

    function add() {
        //Create an input type dynamically.
        var element = document.createElement("input");
        var element2 = document.createElement("input");
        var element3 = document.createElement("br"); // Create element of <bt/>
        //Assign different attributes to the element.
        element.setAttribute("type", "text");
        element.setAttribute("value", "atrib name");
        element.setAttribute("name", "atrib");
        element2.setAttribute("type", "text");
        element2.setAttribute("value", "default value");
        element2.setAttribute("name", "val");
    
        // the div id, where new fields are to be added
        var bar = document.getElementById("bar");
    
        //Append the element in page (in span).
        bar.appendChild(element);
        bar.appendChild(element2);
        bar.appendChild(element3); // add <br/> element
    }
    

    JSFIDDLE

    UPDATE: - Below DOM element properties can cause browser to perform a reflow operation

    • innerHTML
    • offsetParent
    • style
    • scrollTop

    innerHTML will only trigger a reflow when setting it changes the DOM.

    innerHTML changes the HTML of an object which certainly can affect size and position and will trigger at least a partial reflow.

    See the reference link

    0 讨论(0)
提交回复
热议问题