alt*_*alt 24 javascript dom textnode
我有一个小文本节点:
var node
Run Code Online (Sandbox Code Playgroud)
而且我希望围绕"lol"的每一次出现都包含一个范围.
node.nodeValue = node.nodeValue.replace(/lol/, "<span>lol</span>")
Run Code Online (Sandbox Code Playgroud)
"<span>lol<span>"当我想要"lol"作为span元素时它打印出来.
小智 20
Andreas Josas提出的答案非常好.但是,当搜索项在同一文本节点中出现多次时,代码有几个错误.这是解决了这些错误的解决方案,另外插入因素被考虑到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;
};
Run Code Online (Sandbox Code Playgroud)
用法:
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;
});
Run Code Online (Sandbox Code Playgroud)
如果您希望插入锚点(链接)标签而不是span标签,请将create元素更改为"a"而不是"span",添加一行以将href属性添加到标记,并将"a"添加到excludeElements列表,以便不在链接内创建链接.
小智 17
以下文章为您提供了使用HTML元素替换文本的代码:
http://blog.alexanderdickson.com/javascript-replacing-text
来自文章:
var 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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
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);
});
Run Code Online (Sandbox Code Playgroud)
并解释:
从本质上讲,正确的方法是......
- 迭代所有文本节点.
- 在文本节点中查找子字符串.
- 在偏移处拆分它.
- 在分割之间插入span元素.
您可能需要node成为父节点,这样就可以只使用innerHTML:
node.innerHTML=node.childNodes[0].nodeValue.replace(/lol/, "<span>lol</span>");
Run Code Online (Sandbox Code Playgroud)
这里node.childNodes[0]指的是实际的文本节点,并且node是它的包含元素。
不是说这是一个更好的答案,但我发布了我为完整性所做的事情.在我的情况下,我已经查找或确定了我需要在特定的#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);
Run Code Online (Sandbox Code Playgroud)
对于那些现在发现这个问题的人来说,最新的答案如下:
function textNodeInnerHTML(textNode,innerHTML) {
var div = document.createElement('div');
textNode.parentNode.insertBefore(div,textNode);
div.insertAdjacentHTML('afterend',innerHTML);
div.remove();
textNode.remove();
}
Run Code Online (Sandbox Code Playgroud)
这个想法是在 using 之前插入一个新创建的 html 元素(可以说var div = document.createElement('div');)textNode:
textNode.parentNode.insertBefore(div,textNode);
Run Code Online (Sandbox Code Playgroud)
然后使用:
div.insertAdjacentHTML(
'afterend',
textNode.data.replace(/lol/g,`<span style="color : red">lol</span>`)
)
Run Code Online (Sandbox Code Playgroud)
然后删除textNode并div使用:
textNode.remove();
div.remove();
Run Code Online (Sandbox Code Playgroud)
不会insertAdjacentHTML像 那样破坏事件侦听器innerHTML。
如果您想查找其后代的所有文本节点,elm请使用:
[...elm.querySelectorAll('*')]
.map(l => [...l.childNodes])
.flat()
.filter(l => l.nodeType === 3);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16512 次 |
| 最近记录: |