removeChild() Only Removing One li element

<%= @topic_view.topic.title %>
<%= @topic_view.topic.average_rating %> <%= @topic_view.topic.posts.count { |p| !!p.custom_fields['rating'] } %>

Hello,

Here is my code:

<!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">
    <ul>
      <li><span>X</span>Item 1</li>
      <li><span>X</span>Item 2</li>
      <li><span>X</span>Item 3</li>
    </ul>
  </div>

  <script src="script.js"></script>
</body>
</html>
let span = document.querySelector("span");
let ul = document.querySelector("ul");
let li = document.querySelector("li");

//delete todos
span.addEventListener("click", function(event){
  li.removeChild(span);
  event.stopPropagation();
});

When the span tags are clicked, the X text should go away. By running the code I have, it is only removing the first span only, not the other two. I have tried switching the statement let li = document.querySelectorAll(“li”) to see if that would work, but no luck. How should I proceed to make this work?

querySelectorAll is going to return a node list and you will have to loop through it to get the index of the one you want. You can use a forEach on a node list or turn it into an array and loop through it that way

Here is how I did pretty much the same thing in a project

document.addEventListener('DOMContentLoaded', () => {
const card = document.querySelector('#card-body');
card.addEventListener("click", removeItem);

//Delete item
function removeItem(e) {
  if (e.target.classList.contains("btnDelete")) {
      let cardItems = e.target.parentElement;
      let index = Array.prototype.indexOf.call(card.children, cardItems);
      card.removeChild(cardItems);
  }
}

I call the click function on the div containing all the elements, then got the item that had the class of btnDelete, got the index of the item and removed it.

@jgagan95 What about using event delegation and just delete the element if the nodeName property of the clicked element is “SPAN”?

const ul = document.querySelector("ul");

ul.addEventListener("click", function(event){
  const targetElem = event.target;
  if (targetElem.nodeName === 'SPAN') {
    targetElem.parentNode.removeChild(targetElem);
  }
});