I need to create a simple tooltip library that works like this:
every DOM element with a specific attribute combination (like class="tooltip", data-tooltip-text="some text") automatically displays a tooltip (containing text from data attr) on hover.
This behavior must persist through external DOM manipulation. I really like the idea of utilizing a HTMLcollection for this, for its "live" nature, as iterating the whole DOM with every DOM change sounds potentially very demanding.
Now I would love to watch/listen the collection and run a sequence every time it changes (iterate through the nodes, see if they have a listener, add it if they don't).
How do I do this? The watch and observe methods seem to (if I understand correctly) be capable of that, but they are now deprecated. MDN says that Proxy covers most use cases, but does it cover mine (I haven't found a way to make it work)? Or is there some other way I'm missing?
And what about MutationObserver? I assume that deep-observing the whole application and repeatedly fetching a new NodeList via querySelectorAll with every single change would be too demanding (the library should run over a React application). Dynamically committing the HTMLCollection (as a value) into DOM via React and then (shallowly) listening for changes with MutationObserver might work, but I doubt that would be a good idea either.
mouseover
listener onwindow
and check event.target.closest('.tooltip, [data-tooltip-text="foo"]'), then show the tooltip if it matched an element. As for MutationObserver approach, you don't need to recheck everything, just the changes, see also Performance of MutationObserver to detect nodes in entire DOM – Pneumatic