0

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 = "";
    }
  });
}
0

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you mplungjan, your previous comment actually made me realise what I did wrong. I changed it to this: newLi.appendChild(span); newLi.appendChild(document.createTextNode(newItem)); todoList.appendChild(newLi);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.