2

I made a todo list with some predefined todo list items and I also made it possible to set your own todos inside the list through the prompt command. My problem with this code is, when I try to delete the items that I created, I can't do it. Though I can delete the predefined items. Here's the code:

let addTodo = document.getElementById('add');
let delTodo = document.getElementById('delete');
let ul = document.querySelector('ul');
let li = document.querySelectorAll('li');

addTodo.addEventListener('click', () => {
  let add = prompt('Add a new todo');

  if (add.length >= 1) {
    let newLi = document.createElement('li');
    let newLiText = document.createTextNode = add;
    newLi.append(newLiText);
    ul.appendChild(newLi);
  } else {
    alert('An error has occurred. Please try again.');
  }
});

delTodo.addEventListener('click', () => {
  let deleteTodo = prompt('Which todo do you want to delete?');
  let firstTodo = document.querySelector('#first');
  let secondTodo = document.querySelector('#second');
  let thirdTodo = document.querySelector('#third');

  if (deleteTodo === 'Study') {
    ul.removeChild(firstTodo);
  } else if (deleteTodo === 'Eat') {
    ul.removeChild(secondTodo);
  } else if (deleteTodo === 'Watch') {
    thirdTodo.style.display = 'none';
  } else {
    alert('error occurrred');
  }
});
body {
  margin: 0;
  padding: 0;
  background-color: coral;
  font-family: 'Playfair Display', cursive;
  letter-spacing: 0.1em;
  color: firebrick;
}

.wrapper {
  margin: 10px auto;
  border: 3px solid firebrick;
  max-width: 300px;
  text-align: center;
}

.table {
  margin: 20px auto;
  padding: 10px;
}

.table ul {
  list-style-type: none;
}

.table li {
  text-align: left;
  margin: 20px 0px 20px -40px;
  border: 1px solid red;
  padding: 10px;
}

.table h3 {
  text-align: left;
}

button {
  margin: 10px 10px;
  padding: 5px;
  font-family: 'Playfair Display';
  background-color: coral;
  color: firebrick;
  border: 2px solid firebrick;
}
<!DOCTYPE html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Playfair+Display&display=swap" rel="stylesheet">
</head>

<body>
  <div class="wrapper">
    <h1>Todo List</h1>
    <div class="table">
      <h3>List the todos here</h3>
      <ul>
        <li id="first">Study Math</li>
        <li id="second">Eat Breakfast</li>
        <li id="third">Watch a Movie</li>
      </ul>
    </div>
    <button id="add">Add new todo</button>
    <button id="delete">Delete todo</button>
  </div>
  <script src="sandbox.js"></script>
</body>

</html>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
David
  • 67
  • 6
  • the html you show obviously only handles the 3 preset choices. Have you tried making the delete click handler find all `
  • ` elements instead of hardcoding just those?
  • – Always Learning Feb 22 '20 at 14:19