You are removing all elements because of this excerpt from your code:
document.querySelectorAll('.teste1').forEach(e => e.remove());
He will basically select all added elements and iterate over each of them by removing them individually.
You need to select the last element within the element .teste1
. There are several ways to select the last element.
Using the pseudo selector :last-child
const element = document.querySelector('.teste1 > *:last-child');
if (element) {
element.remove();
}
This will make you select the last child that is inside the first element found with the class .classe1
. For this, we use the pseudo-selector :last-child
.
If your environment endure, you can even use the new syntax of optional chaining (optional chaining), introduced in the latest version of Ecmascript:
document.querySelector('.teste1 > *:last-child')?.remove();
A functional example:
const button = document.querySelector('.remove');
button.addEventListener('click', () => {
const element = document.querySelector('.teste1 > *:last-child');
if (element) {
element.remove();
}
});
<button class="remove">Remover Último</button>
<div class="teste1">
<div>Filho 01</div>
<div>Filho 02</div>
<div>Filho 03</div>
<div>Filho 04</div>
</div>
This is a "native" Javascript API. It’s older, which gives greater support for legacy environments. It is also a little simpler, as no CSS pseudo-selectors are involved.
Behold:
const button = document.querySelector('.remove');
button.addEventListener('click', () => {
const parent = document.querySelector('.teste1');
const element = parent.lastElementChild;
if (element) {
element.remove();
}
});
<button class="remove">Remover Último</button>
<div class="teste1">
<div>Filho 01</div>
<div>Filho 02</div>
<div>Filho 03</div>
<div>Filho 04</div>
</div>
If the environment supports, you can also make use of the new optional chaining syntax to avoid the declaration if
.
Retrieve all children and select the last element of the array
Finally, you can get all children using the API ParentNode.children
, that returns a HTMLCollection
(an array type, but with some differences). From this collection, just get your last element.
Thus:
const button = document.querySelector('.remove');
button.addEventListener('click', () => {
const parent = document.querySelector('.teste1');
const children = parent.children;
const element = children[children.length - 1];
if (element) {
element.remove();
}
});
<button class="remove">Remover Último</button>
<div class="teste1">
<div>Filho 01</div>
<div>Filho 02</div>
<div>Filho 03</div>
<div>Filho 04</div>
</div>
Surely there are more ways to do this, but I will stop here. :)