The estate event.target
refers, in the case of click events, to the element that issued the event in question.
Knowing this, you can use the property target
to verify that the element that activated the event meets a certain condition and, depending on its outcome, allow or discard the event.
Trivially, you can do something like this:
const div = document.querySelector('div#my-div');
window.addEventListener('click', function(event) {
if (event.target.tagName === 'DIV') {
console.log('Evento descartado.');
return;
}
div.remove();
});
#my-div, #my-div * {
border: solid 1px black;
background-color: rgba(0, 0, 0, .05);
}
<div id="my-div">
<p>Paragrafo</p>
<p>Paragrafo</p>
<p>Paragrafo</p>
<p>Paragrafo</p>
<p>Paragrafo</p>
</div>
Notice now that if you click on div
(area marked in light gray), it is no longer removed. However, the effect is not discarded if we click on an element intern à div
, as one of its elements p
, since the verification we are doing does not encompass them.
Therefore, we need to ensure that the target of the event is not the div
in question or one of their children. For this, one can use a while
and check the relatives of target
, thus.
We will then:
const div = document.querySelector('div#my-div');
window.addEventListener('click', function(event) {
// Se o alvo do evento for a div ou um de seus filhos, descarte o evento.
if (event.target === div || isChildrenOf(event.target, div)) {
console.log('Evento descartado.');
return;
}
div.remove();
});
// Função que verifica se `child` é filho de `parent` na hierarquia do DOM.
function isChildrenOf(child, parent) {
let current = child;
while (current = current.parentElement) {
if (current === parent) {
return true;
}
}
return false;
}
#my-div, #my-div * {
border: solid 1px black;
background-color: rgba(0, 0, 0, .05);
}
<div id="my-div">
<p>Paragrafo</p>
<p>Paragrafo</p>
<p>Paragrafo</p>
<p>Paragrafo</p>
<p>Paragrafo</p>
</div>
Bigger back, 100% explanatory and functional, I imagined that there was something with a little less code just imagined but thank you, if this is the only way will serve
– Adriano
Obs I’m not judging or belittling the code, it’s perfect, I just figured there was like a command that did this
– Adriano
@Adriano, although there is no native API equivalent to the function
isChildrenOf
, the code can be reduced with the approach demonstrated in another answer.– Luiz Felipe