Watch for specific added nodes with MutationObserver
A MutationObserver interface picks up on changes to the DOM. But determining whether those changes include the addition of elements of interest takes some digging.
The MutationObserver constructor’s callback function receives an array of MutationRecords. Each MutationRecord has an addedNodes property, a NodeList of the nodes added to the view in the mutation which triggered the callback. Inspect these added nodes to see if any are ones you need to act on.
Say you want to add the attribute
data-initialized to all elements with the class
example. Start with a MutationObserver constructor that watches everything on the page (
subtree: true) for the addition and removal of child nodes (
Then, in the constructor’s callback function, find the nodes of interest and act on them
Where I use the name “mutationRecords” for the array of
MutationRecords, some people use “mutationList”.
If this script comes after markup, take into account elements already on the page
Here’s a CodePen for that