0

I am making a chrome extension to find a string if text in DOM and replace it with something else. What is the best way to traverse the whole DOM element wise and replace the text in DOM. I Thought of placing document.body in a variable and then process it as a qeue but I am confused that how to do so This is my Code:

flag = true;

var word = 'word',//word to replace
  queue = [document.body],
  curr;
try {
  while ((curr = queue.pop()) || flag) {
    if (!(curr.textContent.match(word))
      continue;
    for (var i = 0; i < curr.childNodes.length; ++i) {
      if (!flag) break;
      switch (curr.childNodes[i].nodeType) {
        case Node.TEXT_NODE: // 3
          if (curr.childNodes[i].textContent.match(word)) {
            curr.childNodes[i].textContent("xxx");//replacing the word
            console.log('Found!');
            flag = false;
            break;
          }
          break;
        case Node.ELEMENT_NODE: // 1
          queue.push(curr.childNodes[i]);
          break;
      }
    }
  }

} catch (e) {
  //
}
Salman Arshad
  • 343
  • 6
  • 23
  • Assuming this is a content script, one of the most efficient node traversal techniques is the DOM TreeWalker API, [Javascript .replace command replace page text?](//stackoverflow.com/a/7275856), and there are also efficient customizable libraries such as **mark.js**. – wOxxOm Jun 14 '19 at 11:40
  • Yes Tree Walker API is the way to go Thanks – Salman Arshad Jun 15 '19 at 05:55

1 Answers1

-1

you can do it I think with

function replaceAll(recherche, remplacement, chaineAModifier)
{
   return chaineAModifier.split(recherche).join(remplacement);
}
str = $('body').html()
replaceAll(search_word,replacement,str)
$('body').html(str)

but that will replace everything including html nodes attribute and name

BootEXE
  • 13
  • 4
  • Replacing the entire HTML of the entire page destroys the JS event listeners, [more info](https://stackoverflow.com/a/7275856). – wOxxOm Jun 14 '19 at 11:42