This work is better handled by DOM interactions. The following two functions of the utility will work to wrap each character in a given text with a span tag.
function getTextNodes(node) {
var childTextNodes = [];
if (!node.hasChildNodes()) {
return;
}
var childNodes = node.childNodes;
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeType == Node.TEXT_NODE) {
childTextNodes.push(childNodes[i]);
}
else if (childNodes[i].nodeType == Node.ELEMENT_NODE) {
Array.prototype.push.apply(childTextNodes, getTextNodes(childNodes[i]));
}
}
return childTextNodes;
}
function wrapEachCharacter(textNode, tag) {
var text = textNode.nodeValue;
var parent = textNode.parentNode;
var characters = text.split('');
characters.forEach(function(character) {
var element = document.createElement(tag);
var characterNode = document.createTextNode(character);
element.appendChild(characterNode);
parent.insertBefore(element, textNode);
});
parent.removeChild(textNode);
}
, HTML, DOM, , - getTextNodes. , - wrapEachCharacter.
var container = document.createElement('div');
container.innerHTML = "To Sherlock Holmes she is always <i>THE</i> woman.";
var allTextNodes = getTextNodes(container);
allTextNodes.forEach(function(textNode) {
wrapEachCharacter(textNode, 'span');
});
.