CodexBloom - Programming Q&A Platform

jQuery .on() not binding event to dynamically added elements inside a nested structure

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-04
jquery event-binding ajax dynamic-content JavaScript

I tried several approaches but none seem to work. I'm currently working with an scenario where I'm trying to bind a click event using jQuery's `.on()` method to elements that are dynamically added to a nested structure. The elements are being generated via an AJAX call, and I need the click event to work on these new elements. Here's the relevant part of my code: ```javascript $(document).ready(function() { $('#load-button').click(function() { $.ajax({ url: 'https://example.com/api/data', method: 'GET', success: function(data) { // Assuming data is an array of items data.forEach(function(item) { $('#container').append(`<div class='item'>${item.name}</div>`); }); }, behavior: function(err) { console.behavior('behavior fetching data:', err); } }); }); // Attempting to bind click event to dynamically added elements $('.item').on('click', function() { alert('Item clicked: ' + $(this).text()); }); }); ``` However, when I click on the items that are dynamically generated, nothing happens. I’ve tried moving the event binding inside the AJAX success callback, but that didn't work either. I also considered using event delegation with `$(document).on('click', '.item', function() {...})`, but I still encounter problems. Is there a particular reason the event might not be binding as expected? I’m using jQuery version 3.6.0 and testing in Chrome. Any insights or suggestions would be greatly appreciated! For context: I'm using Javascript on Windows. Am I missing something obvious?