Task 1: Interactive Todo List
📸 Reference Effect
Check out the final effect: View Task 1 Screenshot
🎯 Key Learning Points
Master creating DOM elements dynamically. Learn how to create elements, set their properties, add them to the page, and handle user interactions with dynamically created content.
Task Instructions
- Create the
addTodo(todoText)function:- Step 1: Create a new
lielement usingdocument.createElement('li') - Step 2: Add the 'todo-item' class using
classList.add() - Step 3: Create a
spanelement for the todo text - Step 4: Set the span's
textContentto the todoText - Step 5: Create a delete button element
- Step 6: Set the button's text to '❌ Delete'
- Step 7: Add a click event listener to the button that calls
deleteTodo() - Step 8: Append the span to the li element using
li.appendChild(span) - Step 9: Append the button to the li element
- Step 10: Get the todo list container and append the li to it
- Step 11: Update the todo counter by calling
updateTodoCount()
- Step 1: Create a new
- Create the
deleteTodo(event)function:- Step 1: Get the button that was clicked using
event.target - Step 2: Get the parent
lielement usingparentElement - Step 3: Remove the li element using
li.remove() - Step 4: Update the todo counter
- Step 1: Get the button that was clicked using
- Create the
updateTodoCount()function:- Step 1: Select all todo items using
querySelectorAll('.todo-item') - Step 2: Get the count using the
lengthproperty - Step 3: Update the counter display element
- Step 1: Select all todo items using
- Create the
handleAddTodo(event)function:- Step 1: Prevent form submission
- Step 2: Get the input element and its value
- Step 3: Trim the input value
- Step 4: Check if the input is not empty
- Step 5: If not empty, call
addTodo()with the trimmed value - Step 6: Clear the input field by setting
value = ''
- Set up event listeners:
- Select the todo form and add submit event listener
📝 Example createElement Pattern:
function addTodo(todoText) {
// Create the list item
const li = document.createElement('li');
li.classList.add('todo-item');
// Create and add the text
const span = document.createElement('span');
span.textContent = todoText;
// Append to list item
li.appendChild(span);
// Add to the page
const todoList = document.querySelector('#todo-list');
todoList.appendChild(li);
}
✅ Todo List Demo
🔑 Key Concepts Used
- createElement:
document.createElement('tagName') - Setting Properties:
textContent,className - Appending Elements:
appendChild(element) - Removing Elements:
element.remove() - Parent/Child Navigation:
parentElement