在所有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>