79388767

Date: 2025-01-26 15:31:13
Score: 0.5
Natty:
Report link

createNodeIterator seems to be a way to go.

But I want to add a note and a fix to another answers here.

Recursion way:
The difference from answer https://stackoverflow.com/a/42678415/3273963
is, this will also process Nodes, which don't have children.

function filterNodeRecursively(node) {

    // FILTER_FUNCTION(node) OR STATEMENTS

    for (const childNode of node.childNodes) {
         filterNodeRecursively(node);
    }
}

And also an important note:

childNodes property ... returns a live NodeList (https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)

If a DOM is changed while iterating it with this function. It's not a problem for additions/deletions done ahead of the current position - index, but when a node is added or removed on an index lower than current, next iteration of childNodes will repeat already processed node, or skip node which was not yet selected.

If it's expected that the DOM might change,

to process all nodes in current state, if they don't need to be edited, use cloneNode() before calling this function.

to process all nodes including those added after the filterNodeRecursively() started, and avoid duplicate processing,
Use MutationObserver and also insert/check data-my-mod-done attribute to key nodes.

Reasons:
  • Blacklisted phrase (1): stackoverflow
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
Posted by: papo