Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I remove the clicked "li" Element with eventlistener?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading