document.querySelectorAll('.image').forEach(el => {
el.querySelector('span').addEventListener('click', (e) => {
const clickedElement = e.target;
document.querySelector('.append').append(clickedElement);
});
});
.image {
background: red;
cursor: pointer;
}
.append {
margin-top: 20px;
background: yellow;
}
<div class="image">
<span>image1</span>
</div>
<div class="image">
<span>image2</span>
</div>
<div class="append"></div>
So I am trying to figure it out why when I click image1 or image2 text in red background it appends to yellow background but it disappears from red background? How to stop it from disappearing from red background?
You need to clone the element to make a copy using Node.cloneNode():
const clickedElement = e.target.cloneNode(true);
document.querySelectorAll('.image').forEach(el => {
el.addEventListener('click', (e) => {
const clickedElement = e.target.cloneNode(true);
document.querySelector('.append').append(clickedElement);
});
});
.image {
background: red;
cursor: pointer;
}
.append {
margin-top: 20px;
background: yellow;
}
<div class="image">
<span>image1</span>
</div>
<div class="image">
<span>image2</span>
</div>
<div class="append"></div>
.append() is moving the node itself-- .cloneNode(true) (passed true to clone the subtree as well) will create a copy you can append while leaving the original in place in the DOM:
document.querySelectorAll('.image').forEach(el => {
el.addEventListener('click', (e) => {
const clickedElement = e.target;
const clonedElement = clickedElement.cloneNode(true);
document.querySelector('.append').append(clonedElement);
});
});
.image {
background: red;
cursor: pointer;
}
.append {
margin-top: 20px;
background: yellow;
}
<div class="image">
<span>image1</span>
</div>
<div class="image">
<span>image2</span>
</div>
<div class="append"></div>