我正在寻找一种方法来搜索节点的innerText以寻找匹配的字符串。然后将匹配的文本包装在<span>
中。
要求:
1&gt;该节点可能包含html标签,我希望在匹配的文本选择中维护这些标签。
2&gt;我还希望这在匹配文本上区分大小写。
例如:
This is my <strong>content</strong> to search.
我想找到&#34;我要搜索的内容&#34;
在一个范围内匹配并包裹"my <strong>content</strong> to search"
,结果为:
This is <span>my <strong>content</strong> to search</span>.
此代码仅搜索节点内的完全匹配,如果有html标记(因为这些是其他子节点),则不匹配:
/* Prompt for search */
var text = prompt("Search for:", "");
if (text == null || text.length == 0) return;
/* Remove highlighted results */
var spans = document.getElementsByClassName("labnol");
if (spans) {
for (var i = 0; i < spans.length; i++) {
spans[i].style.backgroundColor = "transparent";
}
}
function searchWithinNode(node, te, len) {
var pos, skip, spannode, middlebit, endbit, middleclone;
skip = 0;
if (node.nodeType == 3) {
pos = node.data.indexOf(te);
if (pos >= 0) {
spannode = document.createElement("span");
spannode.setAttribute("class", "labnol");
spannode.style.backgroundColor = "yellow";
middlebit = node.splitText(pos);
endbit = middlebit.splitText(len);
middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && node.tagName.toUpperCase() != "SCRIPT" && node.tagName.toUpperCase != "STYLE") {
for (var child = 0; child < node.childNodes.length; ++child) {
child = child + searchWithinNode(node.childNodes[child], te, len);
}
}
return skip;
}
searchWithinNode(document.body, text, text.length);