2

I am cloning a div using jQuery and find that events on cloned elements do not work although they work on the original elements. How can I go about this? Note how the answer in the question states that...

"This is how jQuery's clone() method is able to copy a node with its event listeners, for example"

let add = document.getElementsByClassName("add"),
  rem = document.getElementsByClassName("rem"),
  container = document.getElementsByClassName('container')[0];
for (let i = 0; i < add.length; i++) {
  add[i].addEventListener("click", () => {
    $(".cloneable").clone(true, true).appendTo(".container");
  });
}
for (let i = 0; i < rem.length; i++) {
  rem[i].addEventListener("click", () => {
    if (container.childElementCount > 1) {
      $(".cloneable:last").remove();
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="cloneable">
    <div>
      <a class="btn btn-primary add" role="button">Add cell</a>
      <a class="btn btn-primary rem" role="button">Remove cell</a>
    </div>
    <iframe src="index.php"></iframe>
  </div>
</div>
user14773854
  • 303
  • 4
  • 10
  • Does this answer your question? [How to copy a DOM node with event listeners?](https://stackoverflow.com/questions/15408394/how-to-copy-a-dom-node-with-event-listeners) – Ernesto Stifano Apr 23 '22 at 15:09
  • @ErnestoStifano Note that the answer states that "This is how jQuery's clone() method is able to copy a node with its event listeners, for example." – user14773854 Apr 23 '22 at 15:11

1 Answers1

0

ETA: This code clones all elements named ".cloneable", so on second click it creates TWO clones, and so on. You should clone with $('.cloneable:first') or similar.

The issue seems to arise from you binding javascript native events. Using jQuery Events solves your problem.

let add = document.getElementsByClassName("add"),
  rem = document.getElementsByClassName("rem"),
  container = document.getElementsByClassName('container')[0];
for (let i = 0; i < add.length; i++) {
  $(add[i]).on("click", () => {
    $(".cloneable:first").clone(true, true).appendTo(".container");
  });
}
for (let i = 0; i < rem.length; i++) {
  $(rem[i]).on("click", () => {
    if (container.childElementCount > 1) {
      $(".cloneable:last").remove();
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="cloneable">
    <div>
      <a class="btn btn-primary add" role="button">Add cell</a>
      <a class="btn btn-primary rem" role="button">Remove cell</a>
    </div>
    <iframe src="index.php"></iframe>
  </div>
</div>
Shrimp
  • 472
  • 3
  • 9