Q:

Insert  tag using javascript replace

Is it possible to use javascripts replace function to insert a span tag to an html page? 
I've seen examples of scripts that can change a word in an html file using something along the lines of: 
var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    for (var j = 0; j < element.childNodes.length; j++) {
        var node = element.childNodes[j];

        if (node.nodeType === 3) {
            var text = node.nodeValue;
            var replacedText = text.replace(/originalword/gi, 'Different Words');

            if (replacedText !== text) {
                element.replaceChild(document.createTextNode(replacedText), node);
            }
        }
    }
}

However, when I try to add a span tag and change the font color of the original or new word it just shows up with the span tag as text. 
    var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    for (var j = 0; j < element.childNodes.length; j++) {
        var node = element.childNodes[j];

        if (node.nodeType === 3) {
            var text = node.nodeValue;
            var replacedText = text.replace(/originalword/gi, '<span style="color:blue;"> originalword </span>');

            if (replacedText !== text) {
                element.replaceChild(document.createTextNode(replacedText), node);
            }
        }
    }
}

Is it not possible to insert the span tag like this? Or am I just doing something wrong? 

A:

createTextNode: Creates a new Text node. This method can be used to escape HTML characters that's the reason your span is visible in the HTML rather doing the job as HTML.
Instead you can replace the text by using innerHTML as shown below.

var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    for (var j = 0; j < element.childNodes.length; j++) {
        var node = element.childNodes[j];

        if (node.nodeType === 3) {
            var text = node.nodeValue;
            var replacedText = text.replace(/originalword/gi, '<span style="color:blue;"> originalword </span>');

            if (replacedText !== text) {
                element.innerHTML = replacedText;
            }
        }
    }
}
<div>This is an example text which is used to check the replace functionality of JS. It will replace originalword with span tag.</div>

