CodexBloom - Programming Q&A Platform

jQuery .on() not triggering for dynamically added list items with event delegation

๐Ÿ‘€ Views: 18 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-13
jquery event-delegation dynamically-generated-content JavaScript

I'm relatively new to this, so bear with me. I'm a bit lost with I'm upgrading from an older version and I'm sure I'm missing something obvious here, but I'm working with an scenario where I'm trying to add click event listeners to list items that are generated dynamically using jQuery... Initially, I set up the event listener using `$(document).on('click', 'li', function() {...})`, but it doesn't seem to work for items added after the page load. I can see the list items getting added to the DOM, but the click event does not fire on those newly added items. Hereโ€™s a simplified version of my setup: ```html <ul id="myList"> <li>Item 1</li> <li>Item 2</li> </ul> <button id="addItem">Add Item</button> ``` ```javascript $(document).on('click', '#myList li', function() { alert($(this).text()); }); $('#addItem').click(function() { $('#myList').append('<li>New Item</li>'); }); ``` When I click on "Add Item" it adds a new list item, but clicking on that new item does not trigger the alert. Also, I've checked the console for any potential errors, but thereโ€™s nothing that stands out. I'm using jQuery version 3.6.0. I would have expected the event delegation to handle this correctly, so I'm not sure why it's failing. Any insights would be greatly appreciated! This is part of a larger service I'm building. I recently upgraded to Javascript 3.11. What would be the recommended way to handle this? I'm working in a Debian environment. I've been using Javascript for about a year now.