CodexBloom - Programming Q&A Platform

jQuery .on() not capturing nested click events as expected in dynamically added elements

πŸ‘€ Views: 26 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
jquery event-delegation ajax javascript

I need some guidance on After trying multiple solutions online, I still can't figure this out..... I've searched everywhere and can't find a clear answer. I'm working with an scenario where I'm trying to use jQuery's `.on()` method to capture click events on a dynamically added list of items, but it's not firing for nested elements. I have a parent `<div>` that contains a `<ul>`, and each `<li>` has a button inside it. I am using jQuery 3.6.0, and I want the click event to trigger whether the `<li>` is present at page load or added later via AJAX. Here’s my current code: ```javascript $(document).ready(function() { $('#parentDiv').on('click', 'li button', function(event) { event.preventDefault(); console.log('Button clicked!'); }); }); ``` I have verified that the parent div with id `parentDiv` is present and is correctly set up to capture events. However, when I append new `<li>` items dynamically like this: ```javascript $.ajax({ url: 'https://api.example.com/items', method: 'GET', success: function(data) { data.forEach(function(item) { $('#parentDiv ul').append(`<li><button>${item.name}</button></li>`); }); }, behavior: function(xhr, status, behavior) { console.behavior('AJAX behavior:', behavior); } }); ``` The click event doesn't trigger for the buttons in the newly added `<li>` elements. There are no JavaScript errors in the console, and I can see that the buttons are being added to the DOM correctly. I've tried using event delegation with the `.on()` method, but it still doesn't work as expected for these nested buttons. Is there something wrong with my event delegation approach or how I am appending the new elements? Any insights would be greatly appreciated! I'm working on a web app that needs to handle this. Is there a better approach? This is part of a larger service I'm building. What's the best practice here? Any examples would be super helpful.