我正在尝试替换标签之间的所有文本,我想知道最快的方法。
一个例子是尝试用任意字符串 helloWorld 替换所有文本,这样:
<div>
<div>
RandomText1
<div>
RandomText2
</div>
</div>
</div>
就变成这样了:
<div>
<div>
helloWorld
<div>
helloWorld
</div>
</div>
</div>
我目前的方法是:
- 在 DOM 上进行深度优先搜索 (DFS)
- 对于每个元素,解析并确定哪部分是文本,哪部分是元素。
- 对于文本部分,将其替换。
对我来说,这真的很慢,尤其是尝试对大型文档执行此操作并且必须多次重复该过程。有更快的方法吗?
不需要解析每个元素来查找文本节点,只需递归遍历即可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);
<div id='container'>
<div>
RandomText1
<div>
RandomText2
<ul>
<li>RandomText3</li>
</ul>
</div>
</div>
</div>
<button id="replace">Replace</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)