Appending Child Elements to the DOM

Take a look at the JavaScript code in the pen here.

When clicked on the grey box, we get a pink box below. I get that. Now, what’s happening when it’s clicked over and over again? Is the same box being appended every time we click the box? I don’t understand that part.

It’s the same pink box. You can check by Inspect in the Browser (press ctrl + shift + i).

1 Like

Yes, it’s the same box that is being appended. Only if you create the box inside of a function that it another one will be appended, like so:

let triggerBox = document.querySelector(".trigger");

function addClass() {
	let box = document.createElement("div");
	box.classList.add("box");

	triggerBox.appendChild(box);
}
triggerBox.addEventListener("click", addClass);

Additions: if you append an element already in the DOM to another node the element will be moved; a copy is not created.
To make a copy use node.cloneNode(...) - there are other techniques though