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>
Stop propagation works the other way round. You can see how it works here: What's the difference between event.stopPropagation and event.preventDefault?
What you need to do is to get the data from e.currentTarget instead of e.target.
const button = document.querySelector('[data-toggle="collapse"]')
button.addEventListener('click', (e) => {
const target = e.currentTarget.dataset
console.log(target)
}, false);