我正在迭代 html 文档中的所有文本节点,以便用特定的范围包围一些单词。
改变nodeValue
不允许我插入 html。这span
被转义以纯文本显示,我不希望这样。
这是我到目前为止所拥有的:
var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
for (var j = 0; j < element.childNodes.length; j++) {
var node = element.childNodes[j];
if (node.nodeType === Node.TEXT_NODE) {
node.nodeValue = node.nodeValue.replace(/Questions/, "<span>Questions</span>");
}
}
}
<p>Questions1</p>
<p>Questions 2</p>
<p>Questions 3</p>
<p>Questions 4</p>
我认为你需要递归所有 DOM 和每个匹配......看看这里:
function replacer(node, parent) {
var r = /Questions/g;
var result = r.exec(node.nodeValue);
if(!result) { return; }
var newNode = this.createElement('span');
newNode.innerHTML = node
.nodeValue
.replace(r, '<span class="replaced">$&</span>')
;
parent.replaceChild(newNode, node);
}
document.addEventListener('DOMContentLoaded', () => {
function textNodesIterator(e, cb) {
if (e.childNodes.length) {
return Array
.prototype
.forEach
.call(e.childNodes, i => textNodesIterator(i, cb))
;
}
if (e.nodeType == Node.TEXT_NODE && e.nodeValue) {
cb.call(document, e, e.parentNode);
}
}
document
.getElementById('highlight')
.onclick = () => textNodesIterator(
document.body, replacer
);
});
.replaced {background: yellow; }
.replaced .replaced {background: lightseagreen; }
.replaced .replaced .replaced {background: lightcoral; }
<button id="highlight">Highlight</button>
<hr>
<p>Questions1</p>
<p>Questions 2</p>
<p>Questions 3</p>
<p>Questions 4</p>
<p>Questions 5 Questions 6</p>
<div>
<h1>Nesting</h1>
Questions <strong>Questions 4</strong>
<div> Questions <strong>Questions 4</strong></div>
<div>
Questions <strong>Questions 4</strong>
<div> Questions <strong>Questions 4</strong></div>
</div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)