javascriptdomtextnode

Insert HTML into text node with JavaScript


I've got a little text node:

var node

And I want to wrap a span around every occurrence of "lol".

node.nodeValue = node.nodeValue.replace(/lol/, "<span>lol</span>")

It it prints out "<span>lol<span>" when I want "lol" as a span element.


Solution

  • You may need node to be the parent node, that way you can just use innerHTML:

    node.innerHTML=node.childNodes[0].nodeValue.replace(/lol/, "<span>lol</span>");
    

    Here node.childNodes[0] refers to the actual text node, and node is its containing element.