Issue: The elements dynamically added to HTML using a for loop become unresponsive to predefined event listeners

I’m using a self-invoking function with a for loop inside to dynamically add a few elements with JSON data to my HTML document. The function adds the elements just fine, but in its wake they become unresponsive to any predefined event listeners associated with them. Any help would be greatly appreciated.

https://codepen.io/zreticulan/pen/RLmKzV

Self-invoking function:

(function () {
          
          var items = '';
          
          for (var i = 0; i < 5; i++) {
            
            items += '<li><p id="item' + i + '">' + x.query.search[i].title + '</p><a href="https://en.wikipedia.org/?curid=' + x.query.search[i].pageid + '" target="_blank" id="snippet' + i + '" class="hidden">' + x.query.search[i].snippet + ' ...' + '</a></li>';
 
          }
          
          $("#output").html(items);
          
        }) ();

Predefined event listeners:

$("#item0").click(function(){ 
  $("#item0").toggleClass("bold");
  $("#snippet0").toggleClass("hidden");
});

$("#item1").click(function(){ 
  $("#item1").toggleClass("bold");
  $("#snippet1").toggleClass("hidden");
});

$("#item2").click(function(){ 
  $("#item2").toggleClass("bold");
  $("#snippet2").toggleClass("hidden");
});

$("#item3").click(function(){ 
  $("#item3").toggleClass("bold");
  $("#snippet3").toggleClass("hidden");
});

$("#item4").click(function(){ 
  $("#item4").toggleClass("bold");
  $("#snippet4").toggleClass("hidden");
});

try:
$("#output").on(“click”,"#item0",function(){
$("#item0").toggleClass(“bold”);
$("#snippet0").toggleClass(“hidden”);
});

You’ll have to modify them all to have the correct first line of the javascript and see:
Link

I forked your code and tested: here

1 Like

Awesome, this has solved the issue. Thank you!

1 Like