I'll get to the point
What am I trying?: I try to clone items so that every item, when clicked, clones itself. Even those that were cloned.
Problem: The problem is that when I have e.g 10 items cloned, after clicking the first (original) item, it clones the next 10 items. Only the last (newest) clone, clones one element, no matter how many elements I already have.
Info: Without app() at the end of the "clone" function, only the original element adds more clones.
It is problem with clondeNode() or maybe with wrong misaligned addEventListener?
Thanks for the help in advance, Matt
JS:
app = () => {
const divs = document.querySelectorAll('.div');
divs.forEach((div) => {
div.addEventListener('click', () => clone(event))
})
}
clone = (event) => {
const div = event.target;
const clone = div.cloneNode(true);
document.body.appendChild(clone)
app()
}
app()
HTML:
<body>
<div class='div'>DIV FOR CLONING</div>
<script src="main.js"></script>
</body>
When calling app()
after a click, you add a new event listener to all existing elements, which is in addition to the handler they already had attached to them.
Instead of calling app
there, just add the listener to the newly created clone.
Secondly, you use the same name for a function and a variable. That is confusing.
So name that variable differently:
const clonedDiv = div.cloneNode(true);
document.body.appendChild(clonedDiv);
clonedDiv.addEventListener('click', clone);
As you see, you also don't need that arrow function. Just pass clone
as a function argument.