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
Nested button in <a> tag with different onClick event

I have a button that is nested in a tag <a>. Tag <a> has a href attribute and button calls a function. When I click on button, button's function is called and then page is redirected to href. But I want to execute only the button's function and not redirected when I click on button.

<a href='/path/to/somewhere' >
   <div >
     <someElements .... />
     <button onClick='someFunction();' >Click</button>
   </div>
</a>

You can suppose that <a> is a card and href is a path to details information. button can be a like or mark button in the card.

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

0

you can add a click event to the a element and check if the target of the event coming from the button execute preventDefault()

document.querySelector('#link').addEventListener('click', (event) => {
  if (event.target === document.querySelector('#button')) {
    console.log('button clicked')
    event.preventDefault()
  }
})
<a href="https://www.google.com" id="link"><button id="button">button</button></a>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can add the event token to the onClick event and use e.preventDefault() to override the anchor tag event:

function someFunction(e) {
  e.preventDefault()
  console.log('some function executed')
}
<a href='/path/to/somewhere' >
   <div>
     <div>Element 1</div>
     <div>Element 2</div>
     <div>Element 3</div>
     <button onClick='someFunction(event);' >Click Me</button>
   </div>
</a>

It is probably better practices, though, to move the button outside of the anchor tag:

function someFunction() {
  console.log('some function executed')
}
<a href='/path/to/somewhere' >
   <div>
     <div>Element 1</div>
     <div>Element 2</div>
     <div>Element 3</div>
   </div>
</a>
<button onClick='someFunction();' >Click Me</button>

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