Replace a textNode with HTML text in Javascript?

三世轮回 提交于 2019-12-12 07:25:03

问题


I was directed to the Linkify project on GitHub (https://github.com/cowboy/javascript-linkify) for finding and "linkifying" URLs and domains just floating in text.

It's awesome! It totally works on text!

However, I'm not quite sure how to make it work on a textNode which has the text I want to Linkify.

I understand the textNode only has textContent since.. it's all text. Since this Linkify function returns HTML as text, is there a way to take a textNode and "rewrite" the HTML within it with the Linkify output?

I've been playing with it on JSFiddle here: http://jsfiddle.net/AMhRK/9/

function repl(node) {

var nodes=node.childNodes;
for (var i=0, m=nodes.length; i<m; i++)
{
    var n=nodes[i];
    if (n.nodeType==n.TEXT_NODE)
    {
       // do some swappy text to html here?
       n.textContent = linkify(n.textContent);
    }
    else
    {
        repl(n);
    }
}
}

回答1:


You'll need to replace the textNode with an HTML element, like a span, and then set your linkified-text as that element's innerHTML.

var replacementNode = document.createElement('span');
replacementNode.innerHTML = linkify(n.textContent);
n.parentNode.insertBefore(replacementNode, n);
n.parentNode.removeChild(n);



回答2:


Additionally to previous answer I propose more short way (based on jQuery):

$(n).replaceWith('Some text with <b>html</b> support');

where n - is textNode.

Or the native version

var txt = document.createElement("span");
txt.innerHTML = "Some text with <b>html</b> support";
node.replaceWith(txt);

where node is the textNode



来源:https://stackoverflow.com/questions/15553280/replace-a-textnode-with-html-text-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!