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

i write a jquery code but it doesnt work as i expected

I want when I click on add to add an elements in the .items and then when I click "remove" remove it but it doesn’t work

$('.add').on('click', function () {
      $('.items').append('<span class="rmv">remove</span>');
});
$('.rmv').on('click', function() {
       $(this).remove(); 
});
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="items"></div>
<div>
   <span class="add">add</span>
</div>

>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

You are trying to add an event listener to the rmv class before the elements with that class have been added to the page , you can use the $(document).on(‘click’, …) method to attach the event listener to the document instead.

$('.add').on('click', function () {
  $('.items').append('<span class="rmv">remove</span>');
});

$(document).on('click', '.rmv', function() {
   $(this).remove(); 
});
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