What is the simplest treewalker to replace one character in a character or a word in a word?

I am having trouble learning about JavaScript treewaler perhaps due to their syntax being quite different than that of “regular” or “common” JavaScript and probably also because they include for...of syntax which kind of breaks the variable name = x pattern I am used to.

What is the simplest treewalker to replace one character in a character or a word in a word?

By simplest I mean, no for...of, no function() and no else.

Just 1-4 lines of code which replaces a any character in any other character or any word in any other word, in an element, recursively.

Well you need some kind of loop to consume the tree walker, which in essence is done by calling nextNode() until there are no more nodes to show. The mdn suggests a while loop:

let node = treeWalker.currentNode

while (node) {
  // Do something with the node
  node = treeWalker.nextNode()
}

A for loop is just bit nicer IMHO as you then have the initial assignment, the break condition and the iteration step in the same statement, but the general approach is the same…

for (
  let node = treeWalker.currentNode; 
  node; 
  node = treeWalker.nextNode()
) {
  // Do something with the node
}

Thanks a lot !

I thought that treeWalker keyword is by itself a loop.
Good to know that at least with the current release of EcmaScript, it isn’t.

One thing that I still miss is why writing

node;

between:

let node = treeWalker.currentNode;
and
node = treeWalker.nextNode().

1 Like

str.replaceAll ?

(Why are we reinventing the wheel?)

That is a part of the for loop syntax, and is partly why I prefer the while loop instead.

1 Like

I don’t reinvent the wheel.

Every code example I’ve read in this context was either done with innerHTML (which as you know can be very destructive) or with a tree walker.

Oh I see. You’re saying you want to replace strings globally within a space, but to ignore certain parts of it such as HTML tags.

Yeah… any sort of XML/HTML walker is going to use a loop, either expressly written, hidden inside functions, or array manipulation. for, while, foreach, etc.

Anything which replaces is by nature destructive.
As for the TreeWalker object visit https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
That will explain how the TreeWalker interface works and it is TreeWalker not tree walker

I assume you suggest me and not “commanding me”, you are welcome to correct me if I was wrong.

Anyway, I meant to the general concept of tree walking, of course I agree that in the JavaScript concept it’s TreeWalker and it’s start with a capital letter due to being a built-in object such as Math.