I'm trying to add event listeners to buttons on a webpage, my button contains several child elements, when I click my button I only need to get the data associated with the button, such as data attributes.
Even after adding an event.stopPropogation()
into my on click handler, I'm still seeing that when I click directly over a h2
element that there's no data attributes logged.
What am I exactly missing from my code?
const button = document.querySelector('[data-toggle="collapse"]')
button.addEventListener('click', (e) => {
e.stopPropagation()
const target = e.target.dataset
console.log(target)
}, false)
<body>
<button type="button" data-target="hello" data-toggle="collapse">
<div class="row">
<div class="col">
<h2>
My heading 2
</h2>
</div>
</div>
</button>
</body>