更快地替换所有dom元素中的文本?

Dar*_*zuh 5 html javascript html5 dom dom-traversal

我正在尝试替换标签之间的所有文本,我想知道最快的方式.

一个例子是尝试用任意字符串helloWorld替换所有文本,这样:

<div>
    <div>
        RandomText1
        <div>
            RandomText2
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

变成这样:

<div>
    <div>
        helloWorld
        <div>
            helloWorld
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我目前的做法是:

  • 在DOM上进行深度优先搜索(DFS)
  • 对于每个元素进行解析并确定哪个部分是文本以及哪个部分是元素.
  • 对于文本部分替换它.

这对我来说非常慢,特别是尝试为大型文档执行此操作并且必须多次重复此过程.有更快的方法吗?

jet*_*ony 5

您不需要解析每个元素来查找文本节点,您只需递归遍历childNodes元素的属性即可

var newText = 'hello world';
function replaceTextNodes(node) {
  node.childNodes.forEach(function(el) {
    if (el.nodeType === 3) {  // If this is a text node, replace the text
      if (el.nodeValue.trim() !== "") { // Ignore this node it it an empty text node
        el.nodeValue = newText;
      }
    } else { // Else recurse on this node
      replaceTextNodes(el);
    }
  });
}

var onClick = replaceTextNodes.bind(null, document.querySelector('#container'));
document.querySelector('#replace').addEventListener('click', onClick);
Run Code Online (Sandbox Code Playgroud)
<div id='container'>
  <div>
    RandomText1
    <div>
      RandomText2
      <ul>
        <li>RandomText3</li>
      </ul>
    </div>
  </div>
</div>
<button id="replace">Replace</button>
Run Code Online (Sandbox Code Playgroud)