0

I have made some code to fire some instructions after a click on an html element :

const datepicker = document.querySelector(".datepicker")
datepicker.addEventListener("click", () => {
//ajax request
}

The click on the element generates some more html elements through javascript (it displays a datepicker). How can I add another Eventlistener on the newly created element document.queryselector(".month-next") by the previous click ? edit : I use materialize datepicker, the "month-next" class is generated by the materialize javascript

  • Please show the code you are using to create the elements. – Unmitigated Jul 10 '21 at 19:02
  • The same way. Get a reference of the element and call `.addEventListener()`. But unless these elements are newly created in the "datepicker" click handler these event handlers should only be added once when the "datepicker" is generated. – Andreas Jul 10 '21 at 19:02
  • 1
    Does this answer your question? [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) – Louys Patrice Bessette Jul 10 '21 at 19:02
  • I have edited my question. I don't think this answers my question @LouysPatriceBessette – Arnaud NaNo Jul 10 '21 at 19:08

1 Answers1

1

I don't think this answers my question

The only variant here is to check for a class instead of an id.

// Set an event handler using delegation
document.addEventListener('click', function(e) {
  if (e.target && e.target.classList.contains('brnPrepend')) {
    console.log("Click!")
  }
});


// Append a dynamic element to DOM
setTimeout(function() {
  let dynamicElement = document.createElement("div")
  dynamicElement.innerText = "CLICK ME"
  dynamicElement.classList.add("brnPrepend")
  document.querySelector("body").append(dynamicElement)
}, 2000)
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64