PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 9, 2022

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

 November 09, 2022     html, javascript     No comments   

Issue

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

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>



Answered By - mplungjan
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing