JSFiddle - React, Tailwind, and code Playground

by salman

HTML

<p>See console</p>

JavaScript

function replaceTextWithSpan(node, text, options) {
    var searchText = text.toLowerCase(),
        currentNode = node.firstChild,
        matchIndex,
        newTextNode,
        newSpanNode;
    while (currentNode) {
        matchIndex = currentNode.nodeType === currentNode.TEXT_NODE
            ? currentNode.data.toLowerCase().indexOf(searchText)
            : -1;
        if (matchIndex >= 0) {
            newTextNode = currentNode.splitText(matchIndex);
            currentNode = newTextNode.splitText(searchText.length);
            newSpanNode = document.createElement("span");
            newSpanNode.className = options.className;
            currentNode.parentNode.insertBefore(newSpanNode, currentNode);
            newSpanNode.appendChild(newTextNode);
        } else {
            currentNode = currentNode.nextSibling;
        }
    }
}
var node = document.createElement("div");
node.innerHTML = "Size: 40; Color: 30";
replaceTextWithSpan(node, "Size", { className: "tooltip" });
replaceTextWithSpan(node, "Color", { className: "tooltip" });
console.log(node.innerHTML);