0

I'm using jquery to click toggle a list element created with createElement() but it doesn't work. The html elements display correct but the click function doesn't fire.

$.getJSON(endpoint, function(result) {

    $.each(result, function (i, v) {

        if(v.comment !== null){
            listItem = document.createElement("div");
            listItem.classList.add('row','comment-item');
            listItem.innerHTML = '<div id="toggle-comment-options"><ul id="comment-options" style="display:none"><li>Edit</li><li>Delete</li></ul></div>';
            document.getElementById("comments").appendChild(listItem);
        }

    });

});

$("#toggle-comment-options").click(function(){
    var list = $("#comment-options");
    $(list).fadeToggle();
});
Thiago M.
  • 33
  • 5
  • javascript runs asynchronous, so probably the click handler is set before the element is created. You could try to add the setting of your click handler inside of the getJSON callback, but it could still run to fast. Better of creating the element with jquery which gives you an instance of the element right away. – Gijs Beijer Feb 16 '22 at 15:03
  • 1. Use a delegated event handler - see the duplicate for more info. 2. All the `div` and `ul` elements you create in your loop will have the same `id` which is invalid; they must be unique. If you want to group elements by behaviour, use a `class` instead. – Rory McCrossan Feb 16 '22 at 15:17

0 Answers0