Why doesn't jquery delete work for dynamically added rows?

I am new to jQuery.

Do you guys know why .remove() does not work for strings added with the add button? It works differently for existing elements, such as <li>One</li> .

 <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script> $(document).ready(function(){ $('.more').click(function(){ html_frag='<li>XXX<input type="submit" value="Remove" class="testing" /></li>'; $('ul li:last').after(html_frag); return false; }); }); $(document).ready(function(){ $('.testing').click(function(){ $(this).remove(); return false; }); }); </script> </head> <body> <ul> <li> One <input type="submit" value="Remove" class="testing" /> </li> </ul> <input type="submit" value="Add" class="more" /> </body> </html> 
+4
source share
2 answers

Since the newly added elements do not exist in the DOM when you bind this handler. Try using delegated events as shown below.

  $(document).ready(function(){ $(document).on('click', '.testing', function(){ $(this).remove(); return false; }); }); 
+3
source

try this, it will not work because you are creating the element dynamically since the dynamically created element is used or works in jquery.

  $("body").on("click", ".testing", function(event){ $(this).remove(); return false; }); 
0
source

Source: https://habr.com/ru/post/1443782/


All Articles