Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
Javascript event.stopPropogation is still triggering for child element of a button

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>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);

Also: Difference between e.target and e.currentTarget

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda