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

196
Views
Adding an 'onclick' event to a button created by javascript

i have a card that is created every time a button is pressed, one of the parts of the card is the remove icon. I want to remove the card when the remove button is clicked. i am using this code:

let icon = document.createElement('span');
    icon.className = "span_x";
    document.getElementsByClassName('close')[0].appendChild(icon);
    document.getElementsByClassName('span_x')[0].innerHTML = '<i class="fa fa-remove"></i>';
    icon.addEventListener('click', removeTask());

i tried the last line of code in a few ways, like:

icon.onclick = function()
icon.setAttribute("onclick","removeTask()");

but whatever i'm trying, it always runs the function when creating the card (task), even though i didn't clicked on the icon. i hope i'm being clear enough. thank you for your help.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try this:


xBtn.addEventListener('click', removeTask);

about 4 years ago · Juan Pablo Isaza Report

0

You need to remove the brackets. You're invoking the function right away, when you just need to pass a reference to it

icon.setAttribute("onclick", removeTask)

const removeTask = () => {
  console.log('clicked')
}

let icon = document.createElement('span');
icon.className = "span_x";
document.getElementsByClassName('close')[0].appendChild(icon);
document.getElementsByClassName('span_x')[0].innerHTML = '<i class="fa fa-remove"></i>';
icon.addEventListener('click', removeTask);
.close {
  width: 100px;
  height: 100px;
  background: green;
}

.span_x:after {
  content: 'Click'
}
<div class="close"></div>

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!