在所有dom元素中替换文本的更快方法? [英] Faster way of replacing text in all dom elements?

查看:127
本文介绍了在所有dom元素中替换文本的更快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换标记之间的所有文本,并且我想知道这样做的最快方法.

I'm trying to replace all text in between tags and I want to know the fastest way of doing so.

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

An example would be trying to replace all text with the arbitrary string helloWorld, so that this:

<div>
    <div>
        RandomText1
        <div>
            RandomText2
        </div>
    </div>
</div>

成为这个:

<div>
    <div>
        helloWorld
        <div>
            helloWorld
        </div>
    </div>
</div>

我当前的做法是:

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

这对我来说真的很慢,尤其是尝试对大型文档执行此操作,并且必须重复多次该过程时.有没有更快的方法?

This to me would be really slow, especially trying to do this for a large document and having to repeat the process many times. Is there a faster way?

推荐答案

无需解析每个元素即可找到文本节点,只需递归遍历

You don't need to parse each element to find text nodes, you can just recursively traverse childNodes property of an element

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);

<div id='container'>
  <div>
    RandomText1
    <div>
      RandomText2
      <ul>
        <li>RandomText3</li>
      </ul>
    </div>
  </div>
</div>
<button id="replace">Replace</button>

这篇关于在所有dom元素中替换文本的更快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆