gpt4 book ai didi

javascript - 如何使用javascript修改文本节点的内容?

转载 作者:行者123 更新时间:2023-11-30 17:20:58 25 4
gpt4 key购买 nike

我正在使用 javascript 编写一个浏览器扩展来突出显示关键词。到目前为止,我已经过滤了 DOM 树以获取所有叶节点。但是我在修改这些节点时遇到问题,因为它们是叶节点 ( nodeType == 3 )。 node.nodeValue = '<em>keyword</em> is highlighted'不起作用,因为尖括号被转义了。 replaceChild也不能工作,因为类似 '<em>keyword</em> is highlighted' 的东西不是单个节点,而是实际上是节点的集合,我不想将它们包装到一个节点中。

最佳答案

一些基本的 DOM 操作就可以做到。使用文本节点 splitText()方法两次创建三个文本节点,将包含关键字的中间文本节点移动到突出显示元素并插入 <em>其余两个文本节点之间的元素。

示例

现场演示:http://jsfiddle.net/6228e/

HTML:

<div id="example">This text contains a keyword to highlight</div>

JavaScript 高亮关键字:

var div = document.getElementById("example");
var textNode = div.firstChild;
var keyword = "keyword";
var keywordIndex = textNode.data.indexOf(keyword);
if (keywordIndex > -1) {
// First, split at the start of the keyword
var keywordTextNode = textNode.splitText(keywordIndex);

// Now split off the section after the keyword
var textNodeAfterKeyword = keywordTextNode.splitText(keyword.length);

// We now have three text nodes containing the text before the keyword,
// the keyword itself and the text after the keyword.

// Create the highlight element and put the keyword text node inside it
var highlightEl = document.createElement("em");
highlightEl.appendChild(keywordTextNode);

// Insert the highlight element and we're done
div.insertBefore(highlightEl, textNodeAfterKeyword);
}

这仅适用于包含包含单个关键字的单个文本节点的元素的特定情况。有关更通用的解决方案,请参阅

https://stackoverflow.com/a/10618517/96100

关于javascript - 如何使用javascript修改文本节点的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25136861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com