JSFiddle - React, Tailwind, and code Playground
by Chetan Hanumantha
HTML
<input type="text">
<button>Add Todo</button>
<ul>
</ul>
JavaScript
var inputEl = document.querySelector('input');
var buttonEl = document.querySelector('button');
var ulEl = document.querySelector('ul');
var todos = [
{id: Math.random(),value:'gather requirements'}, {id:Math.random(),value:'usability tests'}
];
buttonEl.addEventListener('click', addTodo);
ulEl.addEventListener('click', removeTodo);
for(var todo of todos){
var todoLi = document.createElement('LI');
todoLi.textContent = todo.value;
todoLi.dataset.id = todo.id;
ulEl.appendChild(todoLi);
}
function addTodo(event) {
var userInput = inputEl.value;
if(userInput.trim() === ''){
return;
}
var newTodo = {id: Math.random(), value: userInput};
var todoLi = document.createElement('LI');
todoLi.textContent = newTodo.value;
todoLi.dataset.id = newTodo.id;
ulEl.appendChild(todoLi);
todos.push(newTodo);
console.log(todos);
}
function removeTodo(event) {
var todoEl = event.target;
var id = todoEl.dataset.id;
console.log('remove id: '+id);
for(var i=0; i< todos.length; i++){
console.log('todos[i].id: '+todos[i].id);
if(todos[i].id == id){
todos.splice(i, 1);
break;
}
}
event.target.parentNode.removeChild(todoEl);
console.log(todos);
}