Replace a textNode with HTML text in Javascript?

后端 未结 2 1903
抹茶落季
抹茶落季 2021-01-07 18:37

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.

相关标签:
2条回答
  • 2021-01-07 18:57

    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);
    
    0 讨论(0)
  • 2021-01-07 18:59

    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

    0 讨论(0)
提交回复
热议问题