Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda