Home > Enterprise >  Delete child element of a div onclick?
Delete child element of a div onclick?

Time:01-29

what I have

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

<div >
  <div > abc </div>
  <div > def </div>
  <div > ghi </div>
  <div > jkl </div>
  <div > 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

CodePudding user response:

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 >
  <div > abc </div>
  <div > def </div>
  <div > ghi </div>
  <div > jkl </div>
  <div > mno </div>
</div>

CodePudding user response:

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 >
  <div > abc </div>
  <div > def </div>
  <div > ghi </div>
  <div > jkl </div>
  <div > mno </div>
</div>

  • Related