How to get a treewalker to skip elements where a user writes text?

35 Views Asked by At

Lexical is a JavaScript text editor that doesn't use the standard input tags to type the text in.

I have created a chrome extension where I do a word find and replace by targeting node.textContent. I'd like to omit text typed inside the lexical text editor.

function replaceBadWords(node, searchedWord, replacement) {
  const treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
  while (treeWalker.nextNode()) {
    const node = treeWalker.currentNode;
    node.textContent = node.textContent.replace(searchedWord, replacement);
  }
}
replaceBaddWords(document.body,`badWord`, `goodWord`);
1

There are 1 best solutions below

0
Grasper On

The JS has a property to check the parentNode if is editable (isContentEditable). This seems to be working well!

if (node.parentNode.isContentEditable === false) {
      node.textContent = node.textContent.replace(searchedWord, replacement);
}