To deal with dynamic DOM elements added after the initial page load in jQuery, you need to use event delegation. You do not attach event handlers directly to dynamic elements but attach them to a parent element that exists in the DOM at page load time and delegate the event to child elements using the.on() method. Here's an example:
$(document).on('click', '.dynamic-class', function() {
// Your event handling code here
};
In this code, the click event is attached to the document, and it listens for clicks on elements with the class.dynamic-class, even if those elements are added dynamically after the page load. This method ensures the event handler works for both existing and new elements.
Best Practice: Attach the event handler to a parent element as close as possible to the target elements for better performance. For example, use a container instead of the document when possible.