Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Handle a click outside of a parent element
// the parent, avoid clicks inside this element
const parent = document.getElementById('parent');
window.addEventListener('click', e => {
let elem =;
// loop through the target's parent nodes to see if it matches
for ( ; elem && elem !== document; elem = elem.parentNode ) {
if(elem === parent) {
// if it matches then get out
return false;
// we know that the click came from outside the parent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment