You should add <li>
elements to the <ul>
, not <div>
elements.
Also, you should use the submit
event. This way you can trigger an add by pressing enter in the input field. Since this is a form, you can make the text required upon submission. This gives you free form validation. The name of the form input should be more specific; try task
instead of input
.
Finally, the addTodo
function should only accept a text string.
const formEl = document.querySelector('form');
const todoUl = document.querySelector('.list');
const pendingSpan = document.querySelector('.pending');
const clearBtn = document.querySelector('.clear');
formEl.addEventListener('submit', (e) => {
e.preventDefault();
addTodo(e.target.elements.task.value.trim());
e.target.reset();
pendingSpan.textContent = todoUl.children.length;
});
todoUl.addEventListener('click', (e) => {
if (e.target.classList.contains('trash')) {
e.target.closest('.todo').remove();
pendingSpan.textContent = todoUl.children.length;
}
});
clearBtn.addEventListener('click', (e) => {
todoUl.innerHTML = '';
pendingSpan.textContent = '0';
});
function addTodo(text) {
// Add LI with class of 'todo'
const todoLi = document.createElement('li');
todoLi.classList.add('todo')
// Create SPAN
const todoSpan = document.createElement('span');
todoSpan.innerText = text;
todoLi.appendChild(todoSpan);
// Create BUTTON
const todoButton = document.createElement('button');
todoButton.innerHTML = `<i class="fa-sharp fa-solid fa-trash trash"></i>`;
todoLi.appendChild(todoButton);
// Append each LI to UL
todoUl.appendChild(todoLi);
}
.todo > span {
display: inline-block;
min-width: 10em;
}
.todo > button > i.trash {
color: red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"/>
<h1>Todo App</h1>
<form autocomplete="off">
<input type="text" name="task" id="task" placeholder="Enter a task..." required>
<button type="submit" class="todo-button"><i class="fa-solid fa-plus plus"></i></button>
</form>
<div class="todo-container">
<ul class="list">
<!--
<div class="todo">
<li>Create something</li>
<button><i class="fa-sharp fa-solid fa-trash trash"></i></button>
</div>
-->
</ul>
</div>
<div class="todo-pending">
<p>You have <span class="pending">0</span> pending task(s)</p>
<button class="clear">Clear All</button>
</div>