0

I'm trying to build a to-do list application with Javascript. But I have a question about creating a new element.

   function todoList() {
  var item = document.getElementById("todoInput").value
  var text = document.createTextNode(item)
  var newItem = document.createElement("li")
  newItem.appendChild(text)
  document.getElementById("list").appendChild(newItem)
}

It's my javascript code. It's working, I can create a li from an input value. But I want to include a delete icon all li items. like this:

<ul id="list">
  <li>New item <i class="fa fa-trash-o de"></i> </li>
</ul>

Thanks.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
Ramazan Erikli
  • 147
  • 1
  • 5
  • 16

2 Answers2

1

Since your question badge is not about css but javascript, I guessed you needed to know a way to do deletion:

function deleteItem(event) {
  var el = event.target
  el.parentNode.removeChild(el)
}

function todoList() {
  var item = document.getElementById("todoInput").value
  var text = document.createTextNode(item)
  var newItem = document.createElement("li")
  newItem.addEventListener('click', deleteItem, null)
  newItem.appendChild(text)
  document.getElementById("list").appendChild(newItem)
}

document.getElementById("go").addEventListener('click', todoList, null)
<input type="text" id="todoInput">
<button id="go">add todo</button>
<ul id="list">

</ul>

The idea is basically to add an appropriate event listener to every new item. And when this listener is called, it deletes associated item.

Here is a more complete jsfiddle, including styling idea.

DISCLAIMER: there are tons of solution to implement a todo list, mine may not be the best, and you could exercise by finding another way.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
-1

Try this:

function todoList() {
  var item = document.getElementById("todoInput").value
  var text = document.createTextNode(item)
  // Create icon element to append to DOM
  var icon = document.createElement("i");
  icon.classList.add('fa', 'fa-trash-o', 'de');
  var newItem = document.createElement("li")
  newItem.appendChild(text)
  newItem.appendChild(icon)
  document.getElementById("list").appendChild(newItem)
}
Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26