0

Is there a way to have a clickable div with a nested <a>, that doesn't execute the click event on the div when the <a> tag is clicked?

Looking for a vanilla JS solution

const div = document.querySelector('div');
div.addEventListener('click', e => {
  this.console.log('clicked the div');
});
div {
  width: 300px;
  border: 2px solid green;
  padding: 1em;
}
<div> 
<p>This is a button</p>
<a href="/" target="_blank">Link to somewhere else</a>
</div>
SaroGFX
  • 699
  • 6
  • 20

1 Answers1

2

You can check what element was the target of the event.

const div = document.querySelector('div');
div.addEventListener('click', e => {
  if(!e.target.matches('a'))
    console.log('clicked the div');
});
div {
  width: 300px;
  border: 2px solid green;
  padding: 1em;
}
<div> 
<p>This is a button</p>
<a href="/" target="_blank">Link to somewhere else</a>
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80