Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!