JS Frameworks

Why?

by smax

HTML

<input type="text">
<button>Add ToDo</button>

<ul>
  
</ul>

JavaScript

var buttonEl = document.querySelector('button');
var inputEl = document.querySelector('input');
var ulEl = document.querySelector('ul');

var todos = [];

buttonEl.addEventListener('click', addTodo);

function addTodo() {
	var userInput = inputEl.value;
  if (userInput.trim() == '') {
  	return;
  }
  
  var newTodo = {id: Math.random(), value: userInput};
  todos.push(newTodo);
  var todoLi = document.createElement('LI');
  todoLi.textContent = userInput + ' ';
  var removeLink = document.createElement('A');
  removeLink.textContent = '(remove)';
  removeLink.href = '#';
  removeLink.addEventListener('click', removeTodo);
  todoLi.dataset.itemId = newTodo.id;
  todoLi.appendChild(removeLink);
  ulEl.appendChild(todoLi);
  console.log(todos);
}

function removeTodo(event) {
	var target = event.target.parentNode;
  var itemId = target.dataset.itemId;
  target.parentNode.removeChild(target);
  for (var i = 0; i < todos.length; i++) {
  	if (todos[i].id == itemId) {
    	todos.splice(i, 1);
    }
  }
  console.log(todos);
}