Search code examples
javascriptdomonclickappendchildcreateelement

Why a new node added by appendChild diasppears after leaving the function?


Please look at the following code:

**page.html**:
    <!DOCTYPE html>
    <html>
    <head>
        <title> Playing with JavaScript </title>
        <script src="myjs.js"> </script>
    </head>

<body id="body">

<ul id="mylist">
    <li> David </li>
    <li> Aharon </li>
</ul>

<form>
<input type="text" name="user_input"> <br>
<button onclick="add_item(user_input.value)"> add_item </button>
</form>

</body>
</html>


**myjs.js**    
function add_item(user_input) {
        var new_li = document.createElement("li");
        var new_text = document.createTextNode(user_input);
        new_li.appendChild(new_text);
        document.getElementById("mylist").appendChild(new_li);
    }

This code creates a list of two names and displays a button and an input line. Once the user enters a new name in the input line and clicks the button, the new name is supposed to be added to the list.

It happens for a very short period of time and then the new element in the list disappears. Do you know what can I change in the code so the new element in the list will stay permanently?


Solution

  • I think it's because your form is submited and page is reload

    add a type="button" at your button

    Working Example

    function add_item(user_input) {
      var new_li = document.createElement("li");
      var new_text = document.createTextNode(user_input);
      new_li.appendChild(new_text);
      document.getElementById("mylist").appendChild(new_li);
    }
    <form>
      <input type="text" name="user_input"> <br>
      <button type="button" onclick="add_item(user_input.value)"> add_item </button>
    </form>
    <ul id="mylist"></ul>

    <button> element have 3 type :

    • submit : default type if no type are specified who submit a form
    • reset : who reset/clear input in a form
    • button : no specific action