我有一个小文本节点:
var node
而且我希望把每个“lol”用标签包围起来。
node.nodeValue = node.nodeValue.replace(/lol/, "<span>lol</span>")
当我想要一个元素时,它会打印出"<span>lol</span>
"而不是"lol"。
我有一个小文本节点:
var node
而且我希望把每个“lol”用标签包围起来。
node.nodeValue = node.nodeValue.replace(/lol/, "<span>lol</span>")
当我想要一个元素时,它会打印出"<span>lol</span>
"而不是"lol"。
安德烈亚斯·乔萨斯提供的答案非常好。然而,当搜索词在同一个文本节点中出现多次时,该代码存在几个错误。这里是修复了这些错误的解决方案,此外插入已经被分解到matchText中以便于更容易使用和理解。现在只有新标签在回调函数中构建并通过返回传递给matchText。
更新后的matchText函数,已修复错误:
var matchText = function(node, regex, callback, excludeElements) {
excludeElements || (excludeElements = ['script', 'style', 'iframe', 'canvas']);
var child = node.firstChild;
while (child) {
switch (child.nodeType) {
case 1:
if (excludeElements.indexOf(child.tagName.toLowerCase()) > -1)
break;
matchText(child, regex, callback, excludeElements);
break;
case 3:
var bk = 0;
child.data.replace(regex, function(all) {
var args = [].slice.call(arguments),
offset = args[args.length - 2],
newTextNode = child.splitText(offset+bk), tag;
bk -= child.data.length + all.length;
newTextNode.data = newTextNode.data.substr(all.length);
tag = callback.apply(window, [child].concat(args));
child.parentNode.insertBefore(tag, newTextNode);
child = newTextNode;
});
regex.lastIndex = 0;
break;
}
child = child.nextSibling;
}
return node;
};
用法:
matchText(document.getElementsByTagName("article")[0], new RegExp("\\b" + searchTerm + "\\b", "g"), function(node, match, offset) {
var span = document.createElement("span");
span.className = "search-term";
span.textContent = match;
return span;
});
如果您希望插入锚点(链接)标记而不是 span 标记,请将创建元素更改为 "a" 而不是 "span",添加一行来添加 href 属性到标记,并将 'a' 添加到 excludeElements 列表中,以便在链接内部不会创建链接。regex.lastIndex = 0
,以在重用正则表达式时重置它。请参见https://dev59.com/gnI_5IYBdhLWcg3wHfOr。 - JeffsearchTerm
是您要搜索的文本。您提供的回调函数接收 DOM 节点、找到的匹配项和所找到内容的偏移量。然后在回调函数中使用这些信息进行任何您想要的操作,例如替换它、给节点着色、拆分文本并在其周围放置标签,或者您现在知道 searchTerm 在 dom 中确切位置后想要执行的任何其他操作。 - d'Artagnan Evergreen Barbosavar matchText = function(node, regex, callback, excludeElements) {
excludeElements || (excludeElements = ['script', 'style', 'iframe', 'canvas']);
var child = node.firstChild;
do {
switch (child.nodeType) {
case 1:
if (excludeElements.indexOf(child.tagName.toLowerCase()) > -1) {
continue;
}
matchText(child, regex, callback, excludeElements);
break;
case 3:
child.data.replace(regex, function(all) {
var args = [].slice.call(arguments),
offset = args[args.length - 2],
newTextNode = child.splitText(offset);
newTextNode.data = newTextNode.data.substr(all.length);
callback.apply(window, [child].concat(args));
child = newTextNode;
});
break;
}
} while (child = child.nextSibling);
return node;
}
使用方法:
matchText(document.getElementsByTagName("article")[0], new RegExp("\\b" + searchTerm + "\\b", "g"), function(node, match, offset) {
var span = document.createElement("span");
span.className = "search-term";
span.textContent = match;
node.parentNode.insertBefore(span, node.nextSibling);
});
并且解释:
基本上,正确的做法是...
- 遍历所有的文本节点。
- 在文本节点中找到子字符串。
- 在偏移量处将其拆分。
- 在拆分中间插入一个 span 元素。
var child = node.firstChild;
后面应该添加 if (child===null) return;
。 - WW00WW并不是说这是一个更好的答案,但我为了完整性而发布了我所做的事情。在我的情况下,我已经查找或确定了需要在特定的 #text 节点中突出显示的文本的偏移量。这也澄清了步骤。
//node is a #text node, startIndex is the beginning location of the text to highlight, and endIndex is the index of the character just after the text to highlight
var parentNode = node.parentNode;
// break the node text into 3 parts: part1 - before the selected text, part2- the text to highlight, and part3 - the text after the highlight
var s = node.nodeValue;
// get the text before the highlight
var part1 = s.substring(0, startIndex);
// get the text that will be highlighted
var part2 = s.substring(startIndex, endIndex);
// get the part after the highlight
var part3 = s.substring(endIndex);
// replace the text node with the new nodes
var textNode = document.createTextNode(part1);
parentNode.replaceChild(textNode, node);
// create a span node and add it to the parent immediately after the first text node
var spanNode = document.createElement("span");
spanNode.className = "HighlightedText";
parentNode.insertBefore(spanNode, textNode.nextSibling);
// create a text node for the highlighted text and add it to the span node
textNode = document.createTextNode(part2);
spanNode.appendChild(textNode);
// create a text node for the text after the highlight and add it after the span node
textNode = document.createTextNode(part3);
parentNode.insertBefore(textNode, spanNode.nextSibling);
对于现在发现这个问题的人,最新的答案如下:
function textNodeInnerHTML(textNode,innerHTML) {
var div = document.createElement('div');
textNode.parentNode.insertBefore(div,textNode);
div.insertAdjacentHTML('afterend',innerHTML);
div.remove();
textNode.remove();
}
var div = document.createElement('div');
),使用如下技巧将其插入到textNode
之前:textNode.parentNode.insertBefore(div,textNode);
div.insertAdjacentHTML(
'afterend',
textNode.data.replace(/lol/g,`<span style="color : red">lol</span>`)
)
然后使用以下方式删除textNode
和div
:
textNode.remove();
div.remove();
insertAdjacentHTML
不像 innerHTML
那样会销毁事件监听器。elm
的所有文本节点后代,则可以使用以下方法:[...elm.querySelectorAll('*')]
.map(l => [...l.childNodes])
.flat()
.filter(l => l.nodeType === 3);
node
作为父节点,这样您就可以直接使用innerHTML:node.innerHTML=node.childNodes[0].nodeValue.replace(/lol/, "<span>lol</span>");
这里的node.childNodes[0]
指的是实际的文本节点,而node
则是它所在的容器元素。
node.innerHTML
已更改,但UI没有更改。此外,node.parentNode.innerHTML
不包含新更改。 - Jeff