Search code examples
javascriptappendchild

Create span element in li with Javascript


I'm working on a to-do list project and when creating a new li I would like it to start with a span containing a "X". I wrote the code below, but instead of a span I get "[object HTMLSpanElement]". Anybody knows how to fix this? Thank you!


var enterItem = document.querySelectorAll("input");
var todoList = document.getElementById("todo-list");

for (var i = 0; i < enterItem.length; i++) {
  enterItem[i].addEventListener("keypress", function(key) {
    if(key.which === 13){

      var newLi = document.createElement("li");
      var span = document.createElement("span");
      var newItem = this.value;

      span.textContent = "X";
      newLi.appendChild(document.createTextNode(span + " " + newItem));
      todoList.appendChild(newLi);
      this.value = "";
    }
  });
}

Solution

  • You are trying to add an html element in a textNode so it triggers the toString of the element

    You need

    const todoList = document.getElementById("todo-list");
    
    document.getElementById("inputContainer").addEventListener("keypress", function(e) {
      const tgt = e.target;
      if (tgt.type === "text" && e.which === 13) {
        let newLi = document.createElement("li");
        let span = document.createElement("span");
        span.classList.add("remove");
        let newItem = tgt.value;
        span.textContent = "X";
        newLi.appendChild(span)
        newLi.appendChild(document.createTextNode(" " + newItem));
        todoList.appendChild(newLi);
        tgt.value = "";
      }
    });
    
    document.getElementById("todo-list").addEventListener("click", function(e) {
      const tgt = e.target;
      if (tgt.classList.contains("remove")) {
        tgt.closest("li").remove();
      }
    })  
    <div id="inputContainer">
      <input type="text" />
    </div>
    <ul id="todo-list"></ul>