JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<!-- Sets the encoding of the page. -->
<meta charset="UTF-8" />
</head>
<body>
<!-- Heading size 3 -->
<h3>My Todo List</h3>
<!-- ul = Unordered List -->
<ul id="todo-list">
</ul>
<label for="new-item">Add Item</label>
<br> <!-- br = Break Row -->
<input id="new-item-input" placeholder="What's next?">
<br>
<button id="add-item-btn">Add</button>
</body>
</html>
JavaScript
/*
Creates a <li> elemement in memory and returns it.
The returned element is *not* added to the visible DOM.
*/
function createListItem(text) {
// create an empty <li> element
let item = document.createElement('li');
// set the text content of the <li>
item.textContent = text;
// create an empty <button>
let deleteButton = document.createElement('button');
// set the text content of the <button>
deleteButton.textContent = '❌';
/* Called when the delete <button> is clicked. */
function onDeleteClick() {
// Remove the item from the visible DOM.
item.remove();
}
// Add the onDeleteClick function as a listener for the 'click' event
deleteButton.addEventListener('click', onDeleteClick);
// add the <button> inside the <li>
item.appendChild(deleteButton);
// return the <li>
return item;
}
// Get a reference to the <ul id="todo-list"> element from the DOM.
let todoList = document.getElementById('todo-list');
// Create a default list item.
let defaultListItem = createListItem('Learn JavaScript');
// Add that item to the list.
todoList.appendChild(defaultListItem);
// Get a reference to the <input> element.
let newItemInput = document.getElementById('new-item-input');
// Get a reference to the <button> element.
let addItemBtn = document.getElementById('add-item-btn');
/*
Called when the addItemBtn element is clicked.
Reads the value of the input element and
creates and adds an appropriate <li> element
to the list.
*/
function onAddItemClick() {
// Get the value of the <input> (not textContent)
let itemText = newItemInput.value;
// Set the value to the empty string (clear the value).
newItemInput.value = '';
// Create a new item.
let item = createListItem(itemText);
// Add it to the list.
todoList.appendChild(item);
}
// Add the onAddItemClick function as a listener for the 'click' event
addItemBtn.addEventListener('click', onAddItemClick);