Idiot
Idiot

Reputation: 55

Is it possible to remove the child elements of the Ul I have with my code?

On each click of the deleteButton, I want to be able to remove the span and li element from my ul. Here is my code:

let textArea = document.getElementById('textArea');
let submit = document.getElementById("submit")
let ul = document.getElementById("task-list");
let deleteButton = document.getElementsByClassName("deleteButton");

//add todo
submit.addEventListener("click", function(){
  let listItem = document.createElement("li");
  let val = textArea.value;
  listItem.innerHTML = `<button class="deleteButton">X</button> ${val}`;
  ul.appendChild(listItem);
  textArea.value = "";
});

//delete todo
deleteButton.addEventListener("click", function(){
  
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://kit.fontawesome.com/1f5460a8a6.js"></script>
  <link rel="stylesheet" href="style.css">
  <title>Todo List</title>
</head>
<body>
  <div id="container">
    <h1>To-do List</h1>
    <input type="text" id="textArea"><button id="submit">+</button>
    <ul id="task-list">
    </ul>
  </div>
  <script src="script.js"></script>
</body>
</html>

Is it possible with something like I have setup here? Sorry about asking, but I am just stuck and want to become unstuck. I am thinking that using removeChild may work. However, I don’t think it can take both the span and li elements away at the same time.

Upvotes: 1

Views: 103

Answers (2)

Andre Nuechter
Andre Nuechter

Reputation: 2255

You would have to attach an eventHandler on each instance of a delete-button, which you can't the way you're trying, because it's a nodeList and not a single element. I would suggest doing it within the eventHandler on 'submit', like so:

submit.addEventListener("click", function(){
  let listItem = document.createElement("li");
  let val = document.createTextNode(textArea.value);
  let btn = document.createElement('button');

  btn.textContent = 'X';
  btn.onclick = e => e.target.parentNode.remove();

  listItem.append(btn, val);
  ul.appendChild(listItem);
  textArea.value = "";
});

Upvotes: 1

Ibrahim Hasnat
Ibrahim Hasnat

Reputation: 955

Try this. Hope it will work.

document.querySelector("ul").addEventListener("click", function(e) {
  var element = e.target;
  element.remove()
});

Upvotes: 0

Related Questions