Run jQuery after DOM Manipulation


To run a jQuery function after the DOM has been manipulated, you can use the .ready() function or the .on() function with the DOMSubtreeModified event. Here are examples of both approaches:

Using .ready():

$(document).ready(function() {
  // Your code here
});

This function will be called once the DOM has been fully loaded and is ready for manipulation. Any code you place inside the function will be executed after the DOM has been loaded.

Using .on() with DOMSubtreeModified:

$(document).on('DOMSubtreeModified', function() {
  // Your code here
});

This function will be called whenever the DOM is modified, such as when new elements are added or existing elements are updated. Any code you place inside the function will be executed each time the DOM is modified.

Note that the DOMSubtreeModified event is deprecated in jQuery version 3.0 and higher. Instead, you can use the MutationObserver interface to watch for changes to the DOM. Here’s an example:

// Create a new observer
var observer = new MutationObserver(function(mutations) {
  // Your code here
});

// Observe the document for changes
observer.observe(document, { subtree: true, childList: true });

In this example, we create a new MutationObserver object and pass in a function that will be called whenever the DOM is modified. We then call the observe() method to start observing the document for changes, with the subtree and childList options set to true to watch for changes to the document and its children. Any code you place inside the observer function will be executed each time the DOM is modified.