You can add an event to capture all events from click
in the body
, or restrict to a container where all the .box
:
document.querySelector(".container_boxs").addEventListener('click', function(e) {
//...
});
And check in 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 removes the element Parent of the clicked item, in case the .box
:
// remove o parent do item clicado.
e.target.parentElement.remove();
Full 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: "\00d7";
}
.box .close {
background: #ccc;
}
<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>
Complete jsFiddle example.
Credits on the basis of the solution: https://stackoverflow.com/a/9649651/2290538
@Erik that is, you want that when you click on the close, close the box that this close?
– Furlan
Yes. I’d like to remove it.
– Erick Lemos
Are you using jQuery or not ?
– Diego Souza
No. I would like the solution in pure Javascript.
– Erick Lemos
I’m setting an example
– Furlan