The concise guide to using Pagefind for your static site’s search functionality.
Watch for specific added nodes with MutationObserver
Last Updated
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 (target
of document.body
, subtree: true
) for the addition and removal of child nodes (childList: true
)
Then, in the constructor’s callback function, find the nodes of interest and act on them
Other patterns
Where I use the name “mutationRecords” for the array of MutationRecord
s, some people use “mutationList”.
If this script comes after markup, take into account elements already on the page
Here’s a CodePen for that
Generalized pattern
Updates
May 1, 2024: Check children of added nodes.
Articles You Might Enjoy
-
Add high-performance search to static sites with PageFind
-
Accessible CSS-Only Light/Dark Toggles (with JS persistence as progressive enhancement)
CSS’s
:has()
can obviate JS -
Comparing Heroku, Netlify, Vercel, and GitHub Pages for Node.js Projects
Running popular web-based CD tools against each other