I am trying to write a script in vanilla JS (no jQuery) that will remove an element from the page if someone clicks outside of this element.
However, this div
has many nested elements and the way I had it set up is that it disappears even by clicking an element that is within the first element.
Example markup:
<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>
So I would like that no matter how deeply nested an element is, it will check to see if its a descendant of the <div id='parent-node'>
element. So if I click there, it will not get rid of the parent node and all its descendants. The div
and its descendants should ONLY be removed dynamically when clicking outside of the parent div
.
Currently this is what I have and I do know there are some serious fallacies in what I wrote:
function remove(id) {
return (elem = document.getElementById(id)).parentNode.removeChild(elem);
}
document.addEventListener("click", function (e) {
remove('parent-node');
});