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

80
Views
add an event listener on an element I've created in javascript

I'm trying to add event listener to multiples element I created before in my script.

I've tried that method first :

document.body.addEventListener('click', function (event) {
    if (event.target.class === "deleteCommentButton"){
        deleteComment();
    }
})

But it doesn't seems to work, so I'm now trying to do with this method, which seems to be better :

const addEventTobutton = () => {
    document.querySelectorAll('.deleteCommentButton').addEventListener('click', deleteComment);
    document.querySelectorAll('.modifyCommentButton').addEventListener('click', modifyComment);
}

does someone have an explanation for me to understand why my code isn't working ?

thanks

almost 4 years ago · Santiago Trujillo
3 answers
Answer question

0

in your first code you are adding an event listener to the document body, rather than your element. it is not the ideal way to create an event listener, as it is quite inefficient. instead add the listener to the element you want to detect the event on.

const newElement = document.createElement( 'div' );
newElement.addEventListener( 'click', () => {} );

on top of that, to detect an element's class, you should use classList.contains()

if ( newElement.classList.contains( 'deleteCommentButton' ) ) {
almost 4 years ago · Santiago Trujillo Report

0

QuerySelectorAll is an array and therefore, I couldn't add event on it. Need to loop with something like :

  arrayDeleteButton.forEach(deleteBtn => {
        deleteBtn.addEventListener('click', deleteComment)
    });
    arrayModifyButton.forEach(modifyBtn => {
        modifyBtn.addEventListener('click', modifyComment);
    }) 

is this a better solutions than what you guys proposed or should I go your way ?

almost 4 years ago · Santiago Trujillo Report

0

The answer is easy you should use className instead of class for the first approach to work .

That will give all the classes of an element

for that you can use

 event.target.className.contains("deleteCommentButton")
almost 4 years ago · Santiago Trujillo 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!