How to check if some DOM element in another DOM element tree?
For example to hide menu when you click on main page content instead of menu you can:
document.addEventListener(function (e) {
var node = e.target;
do {
if (node.classList.contains('menu-area'))
return;
node = node.parentNode;
} while (node instanceof HTMLElement);
closeMenu();
});
Note that usual solution to hide menu when you click to non-menu area is event.stopPropagation()
on menu and non-conditional document.addEventListener()
.
I make test code with iteration loop over node = node.parentNode
and ===
operator:
<style>
div {
margin: 20px;
padding: 5px;
border: 1px green dotted;
}
</style>
<div id="lvl1">
<div id="lvl2">
<div id="lvl3">
Click me
</div>
</div>
</div>
<div id="result"></div>
<script>
var lvl1Node = document.getElementById('lvl1');
document.addEventListener('click', function(e) {
var node = e.target;
do {
if (lvl1Node === node) {
document.getElementById('result').innerHTML = "Event from: " + e.target.id;
return;
}
node = node.parentNode;
} while (node instanceof HTMLElement);
});
</script>
So only click inside <div id='lvl1'>
change <div id="result">
area. Is that right solution (according to standard)?
That jQuery/Backbone/Underscore/Mojo/etc have to this?