0

I have some HTML that is created dynamically. So the click event not working on that. To solve this I added document before addEventListener in my below code like this

document.acc[i].addEventListener

But it's not working. Can anyone tell how we can add document in this code so that event will work perfectly on the dynamically created elements.

$(document).ready(function () {
    var acc = document.getElementsByClassName("accordion");
    var i;
    for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click", function () {
            this.classList.toggle("active");
            var panel = this.nextElementSibling;
            if (panel.style.display === "block") {
                panel.style.display = "none";
            } else {
                panel.style.display = "block";
            }
        });
    }
});
Michael M.
  • 10,486
  • 9
  • 18
  • 34
atul245
  • 61
  • 7
  • 1
    Please show your HTML. What do you mean by "not working"--is there an error? The code block you show looks generally OK. – ggorlen Aug 17 '22 at 17:59
  • 2
    It should be `document.addEventListener()`, not `document.acc[i].addEventListener()`. – Barmar Aug 17 '22 at 17:59
  • @Barmar "document.addEventListener()" by using this "click event" not working. and we can not skip ".acc[i]". That is my question how I should add document with "acc[i].addEventListener" – atul245 Aug 18 '22 at 03:22
  • @ggorlen. No error is showing , just my click event not working – atul245 Aug 18 '22 at 03:23
  • @ggorlen my given code is ok, But when I add "document." with acc[i].addEventListener then click event stops working – atul245 Aug 18 '22 at 03:24
  • See the linked question for how to do delegation to dynamically added elements. – Barmar Aug 18 '22 at 03:42
  • The code you wrote is running when the page is loaded, before the dynamic elements have been added. – Barmar Aug 18 '22 at 03:44

0 Answers0