Check if clicked element is descendant of parent, otherwise remove parent element
Since event.target
is a reference to the clicked element, you can check to see if #parent-node
is event.target
or if it contains event.target
as a descendant element.
Example Here
In the snippet below, an event listener is attached to the document. If the element that triggered the click event isn't a descendant of #parent-node
and isn't #parent-node
, then the element is removed.
document.addEventListener("click", function(e) {
var element = document.getElementById('parent-node');
if (e.target !== element && !element.contains(e.target)) {
element.parentNode.removeChild(element);
}
});
document.addEventListener("click", function(e) {
var element = document.getElementById('parent-node');
if (e.target !== element && !element.contains(e.target)) {
element.parentNode.removeChild(element);
}
});
#parent-node {
background-color: #f00;
}
<div id='parent-node'>
This is the Master Parent node
<div id='not-parent-node'>
Not Parent Node
<button>Button</button>
<div id='grandchild-node'>
Grandbaby Node
</div>
</div>
</div>
You can use Element.matches()
to determine if the Event.target
has the id #parent-node
or if it is a descendant (#parent-node *
).
Then, you can use ChildNode.remove()
to delete the parent-node
element if the condition is false
:
document.addEventListener('click', event => {
if (!event.target.matches('#parent-node, #parent-node *')) {
document.getElementById('parent-node').remove();
}
});