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>
Saro Verhees
  • 143
  • 11

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
  • 46,070
  • 7
  • 44
  • 60