Search code examples
javascriptappendchild

Adding child element to a parent element using javascript


I am trying to add a child element to a parent element as follows:

  • li to be added to ul
  • Either when the enter button is clicked or the enter key on the keyboard is pressed, a new li and delete button should get added to ul.

My code isn't working right. Can someone help me with this, please?

HTML:

<h1>Simple Add/Remove Task</h1>
<h2>To do List</h2>

<input type="text" placeholder="enter your tasks" id="userInput">
<button id="enter">Enter</button>
<ul>
  <li class="todos">Wake up <button>Delete</button></li>
  <li class="todos">Study<button>Delete</button></li> 
</ul>

CSS:

.done {
  text-decoration: line-through;
}

Javascript:

var listItems = document.querySelectorAll(".todos");
var input = document.getElementById("userInput");
var ul = document.querySelectorAll("ul");
var button = document.getElementById("enter");

button.addEventListener("click", function(){
  if(input.value.length>0){
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
  }
});

input.addEventListener("keypress", function(){
  if(input.value.length > 0 && event.which === 13){
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
  }
});

for (var i = 0; i<listItems.length; i++){
  listItems[i].addEventListener("click", function(){
    this.classList.toggle("done");
  });
}

Solution

  • querySelectorAll returns NodeList. NodeList does not contain appendChild method. So either try to replace ul.appendChild with ul[0].appendChild or just refactor your code