Given the innerHTML of an element, I'm trying to wrap each word in a span, and if the word is already wrapped, wrap the element.
e.g. Such that Here is a paragraph <span class="red">which</span> <div id="typed-effect">might</div> have nested elements
Becomes
<span>Here</span> <span>is</span> <span>a</span> <span>paragraph</span> <span class="red">which</span> <span><div id="typed-effect">might</div></span> <span>have </span> <span>nested</span> <span>elements</span>
The components I have are:
- Extract the innerHTML and wrap in spans:
function wrapElementText(elementSelector) {
const element = document.querySelector(elementSelector);
const rawHTML = element.innerHTML;
// Do magic to create list
element.innerHTML = "";
list.forEach((i, item) => {
if (!item.contains(`<span`)) {
element.innerHTML += `<span class="wrapped-text">${item}</span>`
}
}
};
- My best attempt is this
((\<.*?\>)|((\s?).*?(\s)))
but it's returning e.g.<div id="typed-effect">
andmight</div>
as seperate groups when it should be one group<div id="typed-effect">might</div>
.
Thanks so much in advance!