首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用JavaScript在文本节点中插入超文本标记语言

使用JavaScript在文本节点中插入超文本标记语言
EN

Stack Overflow用户
提问于 2013-05-21 12:55:51
回答 4查看 22.7K关注 0票数 25

我有一个小的文本节点:

代码语言:javascript
复制
var node

我想在每个出现"lol“的地方都加上一个跨度。

代码语言:javascript
复制
node.nodeValue = node.nodeValue.replace(/lol/, "<span>lol</span>")

当我想要"lol"作为span元素时,它会打印出"<span>lol<span>"

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-05-21 13:28:10

您可能需要node作为父节点,这样您就可以只使用innerHTML:

代码语言:javascript
复制
node.innerHTML=node.childNodes[0].nodeValue.replace(/lol/, "<span>lol</span>");

在这里,node.childNodes[0]指的是实际的文本节点,node是它的包含元素。

票数 4
EN

Stack Overflow用户

发布于 2015-03-27 21:23:41

Andreas Josas提出的答案相当不错。但是,当搜索词在同一文本节点中多次出现时,代码有几个bug。这是修复了这些错误的解决方案,此外,为了更容易使用和理解,插入内容被分解到matchText中。现在,只有新标记在回调中构造,并通过返回传递回matchText。

使用错误修复更新了matchText函数:

代码语言:javascript
复制
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;
};

用法:

代码语言:javascript
复制
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标记,请将create元素更改为"a“而不是"span",添加一行以将href属性添加到标记中,并将'a‘添加到excludeElements列表中,这样就不会在链接内创建链接。

票数 20
EN

Stack Overflow用户

发布于 2016-05-12 21:39:14

这并不是说这是一个更好的答案,但我只是为了完整而发布我所做的事情。在我的例子中,我已经查找或确定了需要在特定的#text节点中突出显示的文本的偏移量。这也澄清了步骤。

代码语言:javascript
复制
//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);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16662393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档