Dynamically added Item doesn’t get appended the to the list

Tags: ,



I am trying to append a list item based on the input value. However, the list item doesn’t get appended. I tried to have script tags at different points, but that doesn’t help. What am I missing?

Here is my HTML

<body>
<main>
    <div>
        <form>
            <input type="text" name="newtodo" id="newtodo" placeholder="New Todo...">
            <button type="submit" id="addtodo">+</button>
        </form>
        <div class="AddedTodo">
            <ul id="myList">

            </ul>
        </div>    
        <div>
            <p id="clearAll">Clear All</p>
        </div>
    </div>
</main>
</body>
<script type="text/javascript" src="script.js"></script>

Here is my JavaScript.

document.getElementById("addtodo").onclick = function addItem() {
    var ul = document.getElementById("newtodo").value;
    var li = "<li>" + ul + "</li>";
    document.getElementById("myList").appendChild(li);
}

Answer

You need to use createElement function to create your li to do items. and then use appendChild on that – Also consider using addEventListener

I have also added a functionality of clearAll button. Which will let you clear all to do items from your list.

Also, since you are using a form in your HTML which means the default behaviour is that it will reload the page. To stop that from happening use preventDefault method.

Live Demo:

var list = document.getElementById("myList")

//Add to do's
document.getElementById("addtodo").addEventListener('click', function(e) {
  e.preventDefault()
  var inputValue = document.getElementById("newtodo");
  var li = document.createElement('li')
  li.textContent = inputValue.value
  list.appendChild(li)
  inputValue.value = ''
}, false);


//Clear all
document.getElementById("clearAll").addEventListener('click', function(e) {
  e.preventDefault()
  list.innerHTML = ''
}, false);
<body>
  <main>
    <div>
      <form>
        <input type="text" name="newtodo" id="newtodo" placeholder="New Todo...">
        <button type="submit" id="addtodo">+</button>
      </form>
      <div class="AddedTodo">
        <ul id="myList">

        </ul>
      </div>
      <div>
        <button id="clearAll">Clear All</button>
      </div>
    </div>
  </main>
</body>


Source: stackoverflow