How to duplicate a div onclick event with JavaScript?

Sometimes, we want to duplicate a div onclick event with JavaScript.

In this article, we’ll look at how to duplicate a div onclick event with JavaScript.

How to duplicate a div onclick event with JavaScript?

To duplicate a div onclick event with JavaScript, we can call cloneNode` to clone an element.

Then we can set the onclick property of the cloned element to the same event handler function as the original element.

For instance, we write:

<div id="duplicater">
  foo
</div>

to add a div.

Then we clone it by writing:

let i = 1
const original = document.getElementById('duplicater');
const onClick = () => console.log('clicked')
original.onclick = onClick

const clone = original.cloneNode(true);
i++
clone.id = `duplicater${i}`;
clone.onclick = onClick;
original.parentNode.appendChild(clone);

We select the original element and add a click listener to it with:

const original = document.getElementById('duplicater');
const onClick = () => console.log('clicked')
original.onclick = onClick

Then we deep clone the element by calling cloneNode with true.

Next, we set the ID of the cloned element by setting the id property.

And then we add the click handler by setting clone.onclick to onClick.

Finally, we append it it to the original element’s parent node with original.parentNode.appendChild(clone);.

Conclusion

To duplicate a div onclick event with JavaScript, we can call cloneNode` to clone an element.

Then we can set the onclick property of the cloned element to the same event handler function as the original element.