0

I have a list looking like this. Can I somehow remove just 1 of the li elements with eventlistener and without changing the HTML? I can remove them all by this JS code here under, but I want to remove them in the order I click.

document.querySelector("ol").addEventListener('click', whenClick);

// function to remove rows

function whenClick(event) {
  const li = document.querySelector('.item');
  li.remove();
}
<ol>
  <li class="item">Första</li>
  <li class="item">Andra</li>
  <li class="item">Tredje</li>
  <li class="item" id="fifth">Femte</li>
  <li class="item">Sjätte</li>
</ol>

5
  • use e.currentTarget
    – chovy
    Nov 6, 2022 at 16:37
  • I re-opened since this is not tagged jQuery
    – mplungjan
    Nov 6, 2022 at 16:38
  • @mplungjan - Why? Again, the answers are the same, and now neither of us can add a previous version of the question (you know there are dozens) with DOM only. Such as this one. Nov 6, 2022 at 16:40
  • @mplungjan - I guess I misremembered that you can't dupehammer after reopening. Nov 6, 2022 at 16:42
  • I can still close with the slightly better dupe. My answer seems to be more suited that any of the dupes I could find. Most of them are ancient, uses jQuery or have inline event handlers
    – mplungjan
    Nov 6, 2022 at 16:43

1 Answer 1

-1

Just remove the target

I check if it is an LI

document.querySelector("ol").addEventListener('click', whenClick);

// function to remove rows

function whenClick(event) {
  const tgt = event.target;
  if (!tgt.matches("li")) return
  tgt.remove();
}
<ol>
  <li class="item">Första</li>
  <li class="item">Andra</li>
  <li class="item">Tredje</li>
  <li class="item" id="fifth">Femte</li>
  <li class="item">Sjätte</li>
</ol>

If you have elements inside the LI we can do this

document.querySelector("ol").addEventListener('click', whenClick);

// function to remove rows

function whenClick(event) {
  const tgt = event.target.closest("li");
  if (tgt) tgt.remove();
}
<ol>
  <li class="item"><span>Första</span></li>
  <li class="item">Andra</li>
  <li class="item">Tredje</li>
  <li class="item" id="fifth">Femte</li>
  <li class="item">Sjätte</li>
</ol>

6
  • Massive dupe, as you like to say. Nov 6, 2022 at 16:40
  • @LukasE Varsågod - pls reload to see an extra version
    – mplungjan
    Nov 6, 2022 at 16:40
  • @T.J.Crowder I would normally agree, but the dupes here are not great, use jQuery or inline event handlers
    – mplungjan
    Nov 6, 2022 at 16:45
  • @mplungjan Tack så mycket :D Are you Swedish? :)
    – Lukas E
    Nov 6, 2022 at 20:56
  • Nej, jeg er dansk :)
    – mplungjan
    Nov 7, 2022 at 7:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.