JSFiddle - React, Tailwind, and code Playground
HTML
What?<div>hey hey howdy</div>
This is working... pretty <b>well!</b><br>
<a href="#">Don't wrap these words</a>
<h1>Wrap these though</h1>
CSS
span { background: yellow; }
JavaScript
var wrapWords = function(el) {
var skipTags = {
style: true,
script: true,
iframe: true,
a: true
},
child, tag;
for (var i = el.childNodes.length - 1; i >= 0; i--) {
child = el.childNodes[i];
if (child.nodeType == 1) {
tag = child.nodeName.toLowerCase();
if (!(tag in skipTags)) {
wrapWords(child);
}
} else if (child.nodeType == 3 && /\w+/.test(child.textContent)) {
var si, spanWrap;
while ((si = child.textContent.indexOf(' ')) >= 0) {
if (child != null && si == 0) {
child.splitText(1);
child = child.nextSibling;
} else if (child != null) {
child.splitText(si);
spanWrap = document.createElement("span");
spanWrap.innerHTML = child.textContent;
child.parentNode.replaceChild(spanWrap, child);
child = spanWrap.nextSibling;
}
}
if (child != null) {
spanWrap = document.createElement("span");
spanWrap.innerHTML = child.textContent;
child.parentNode.replaceChild(spanWrap, child);
}
}
}
};
wrapWords(document.body);