You can add an event to capture all events from click
to body
, or restrict to a container where all .box
:
document.querySelector(".container_boxs").addEventListener('click', function(e) {
//...
});
And check this event if the clicked element is in the expected DOM hierarchy:
if (e.target.className.toLowerCase() == 'close' && e.target.parentElement.className.toLowerCase() == 'box') {
alert('Você clicou no elemento close');
}
And finally remove the parent element from the clicked item, in this case .box
:
// remove o parent do item clicado.
e.target.parentElement.remove();
Complete example:
document.querySelector(".container_boxs").addEventListener('click', function(e) {
if (e.target.className.toLowerCase() == 'close' && e.target.parentElement.className.toLowerCase() == 'box') {
// remove o parent do item clicado.
e.target.parentElement.remove();
}
});
.box {
width: 100%;
height: 100px;
border: 1px solid black;
}
.box .close:after {
content: "<div class="container_boxs">
<div class="box">
<div class="close"></div>
</div>
<div class="box">
<div class="close"></div>
</div>
<div class="box">
<div class="close"></div>
</div>
</div>
d7";
}
.box .close {
background: #ccc;
}
document.querySelector(".container_boxs").addEventListener('click', function(e) {
//...
});
Full example jsFiddle.
Solution-based credits: link