An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.
im trying to write a simple script, for a website that often adds elements, that recolors those elements based on criteria.
now, i dont want to have a loop continusly running and checking for new elements, for performance reasons.
how would i use a live HTMLcollectio nand execute a function on every element in it, even the new ones added?
if i can accomplish this, it should result in a script that never finishes, and recolors all new elements.
any help appreciated!
I would use a MutationObserver to accomplish this task. It will watch a node for changes, and if needed it will watch the subtree for changes as well (which I don't think is needed here). As nodes get added, we can send the node to a function to apply some feature on it. In the example below we just randomly select a color and set the background.