I'm trying to use javascript's closest
function on an event.target
element, but it appears that the event.target
loses its parent information from the DOM?
FWIW - I'm detecting clicks on outside of an element body to determine whether or not to close the element.
const hideOnClickOutside = (tag, selector) => {
const isVisible = (element) => {
return element.offsetWidth > 0 || element.offsetHeight > 0;
}
const outsideClickListener = (e) => {
// HERE!!
if (!e.target.closest(selector) && e.target.nodeName != 'BUTTON') {
const element = document.querySelector(selector);
if (isVisible(element)) {
tag.update({visible: false});
document.removeEventListener('click', outsideClickListener);
}
}
}
document.addEventListener('click', outsideClickListener);
}
EDIT:
I appears that a prior event firing has updated the DOM, so the original element e.target
no longer exists. So I guess the question becomes, how do I associate e.target
to the new DOM element that took its place? Using Riotjs
with nested components attaching multiple click events.
EDIT 2:
So if you look in the screenshot, the td
element has a different class than the e.target
element, suggesting the td
elements have in fact been replaced.
I can verify this behavior in https://jsfiddle.net/dainovu3/xuLweLuj/ with a very contrived example that would mimick triggering a re-rendering of the DOM in riot.js whatever other framework.
So... I want to access the parent element of the e.target up the chain of the propogation.
The
event.target
for the second listener is still the original node, not the clone, and by the time that listener runs it's already been removed from the DOM and has no parent anymore.Here's the updated fiddle. If you want to use the clone, you'll have to query the DOM for it in the listener.