简体   繁体   English

在整个DOM中查找和替换文本

[英]Find and replace text in whole DOM

I am making a chrome extension to find a string if text in DOM and replace it with something else. 我正在做一个chrome扩展程序,以查找DOM中的文本(如果是文本)并将其替换为其他字符串。 What is the best way to traverse the whole DOM element wise and replace the text in DOM. 明智地遍历整个DOM元素并替换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: 我想到将document.body放在变量中,然后将其作为队列处理,但是我对如何执行此操作感到困惑,这是我的代码:

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) {
  //
}

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 但这将替换所有内容,包括html节点的属性和名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM