How replace any occurrence of a word in a document?

In all elements, I want to change any “abc” to “xyz” anywhere (case insensitively); i.e. without caring about what’s coming before it or after it, so for example, 1abc1 would still be changed to 1xyz1 and אבגabcאבג would still be changed to אבגxyzאבג).

I tried this which failed:

const pattern = /ערךים/i;
document.querySelectorAll("*").forEach((element) => {
  element.replace(pattern, "ערכים");
});

No ערךים was changed to ערכים anywhere.

How would you suggest to do the change?

Ahoj @bendqh1, if you open the browser console you’ll see an

Uncaught TypeError: element.replace is not a function

This is because querySelectorAll() returns a NodeList, and nodes again don’t have a replace() method. You might replace the textContent though like so:

const walker = document.createTreeWalker(
  document.body, 
  NodeFilter.SHOW_TEXT
)

let node

while ((node = walker.nextNode())) {
  node.textContent = node.textContent.replace('a', 'b')    
}
2 Likes

Wow, thanks.

There are some concepts there I didn’t know before and understand as follows:

  • DOM Tree “walking” concept to somewhat scan the tree as-is in a given time period
  • JavaScript comma operator (which here we use to scan the entire body of the document)
  • Filtering the (scanned body) node with SHOW_TEXT to relate only for nodes with text content
  • While there is a next node to scan this way, do stuff.
1 Like

Glad I could help… which comma operator are you referring to though? The comma after document.body just separates the arguments passed to createTreeWalker(), where the first is the root node from which to start walking, and the second is a bitmask what to show (we only want to operate on text nodes, since modifying the text content of HTML elements will also “flatten” their markup if they have child elements).

1 Like

Yes I meant the comma after document.body.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.