javascriptonclickremovechild

Delete child element of a div onclick?


what I have

I have a parent div of class = "alphabets" and have child div's all with same class = "word"

<div class="alphabets">
  <div class="word"> abc </div>
  <div class="word"> def </div>
  <div class="word"> ghi </div>
  <div class="word"> jkl </div>
  <div class="word"> mno </div>
</div>

what I need when I click on 'abc' it should get deleted, if clicked on 'jkl' it should be deleted, i.e on which text (word) I click it should get deleted.

Help me


Solution

  • use the event.target property to determine which child element was clicked on. Once you know which element was clicked, you can use the remove() method

    const alphabets = document.querySelector('.alphabets');
    
    alphabets.addEventListener('click', (event) => {
      if (event.target.classList.contains('word')) {
        event.target.remove();
      }
    });
    <div class="alphabets">
      <div class="word"> abc </div>
      <div class="word"> def </div>
      <div class="word"> ghi </div>
      <div class="word"> jkl </div>
      <div class="word"> mno </div>
    </div>