简体   繁体   中英

addEventListener not working for dynamic button

I have a dynamically made button, i've set the id and class to try to set an addEventListener but the addEventListener is not read in the DOM but the ID and class is.

here is my code

 let button: HTMLButtonElement = document.createElement('button')

  button.id = "comment-button";
  button.className = "comment-button"; 

(ID & class is working)

Here is what i've tried:

  button.addEventListener("click", setComment);

  document.getElementById("comment-button")?.addEventListener("click", setComment);

To retrieve an element from the document, you need to actually add the element you created to the document. document.body.appendChild(button)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM