Skip to content

Add TODO functionality

Course: DOM Part 2 - chapter 7

Lets add the functionality to

  1. Add more TODOs
  2. Delete functionality

💡 You only need to update state and call the render function. You DONT need to do the actual DOM manipulations, the render function will do it for you.

Solution
<body>
<div id="root"></div>
<div>
<input type="text"></input>
<button onclick="addTodo()">Add Todo</button>
</div>
<script>
let ctr = 2;
let todos = [{
id: 1,
title: "Go to gym"
}, {
id: 2,
title: "Clean the car"
}]
function addTodo() {
todos.push({
id: ctr,
title: document.querySelector("input").value
})
render(todos);
}
function render(todos) {
const todoList = document.getElementById('root');
todoList.innerHTML = ''; // Clear the list
todos.forEach(todo => {
const div = document.createElement('div');
const h1 = document.createElement('h4');
h1.textContent = todo.title;
div.appendChild(h1);
div.setAttribute('data-id', todo.id);
todoList.appendChild(div);
});
}
render(todos)
</script>
</body>