ab" />
ab" />
ab"/>

Delete child element of a div onclick?

58 Views Asked by At

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

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

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>

0
Golam Wasy Arnob On

Another way is to use a jQuery library which provides an easy way for working with the DOM.

$('.word').click(function(){
  $(this).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>