javascript - .clone() create multiple copies -


$(document).ready(function(){      $("button").click(function(){          $("p").clone().appendto("body");      });  });
<head>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  </head>  <body>    <p>this paragraph.</p>  <p>this paragraph.</p>    <button>clone p elements, , append them body element</button>    </body>

<!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){     $("button").click(function(){         $("p").clone().appendto("body");     }); }); </script> </head> <body>  <p>this paragraph.</p> <p>this paragraph.</p>  <button>clone p elements, , append them body element</button>  </body> </html> 

this code produce clones of paragraph, number of clones grow exponentially on first click create 1 copy on second click create 2 clones , on , how fix create 1 copy each time, , how assign new ids each new element created dynamically.

that happens because second time $("p") match, , clone, 4 paragraphs, second time 8 , on. need "mark" original ones or copies. instance can mark "new" items css class , filter them, did in fiddle https://jsfiddle.net/sfarsaci/kb0k7nrx/

$(document).ready(function() {   $("button").click(function() {     $("p:not(.copy)").clone().addclass('copy').appendto("body");   }); }); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -