JSFiddle - React, Tailwind, and code Playground
HTML
<button type="button">Split!</button>
<label>... with span-wrap?<input type="checkbox" /></label>
<p>laborum beatae est nihil, non hic ab, deserunt repellat quas. Est molestiae ipsum minus nesciunt tempore voluptate laboriosam</p>
CSS
p {
margin: 0;
padding: 0;
text-align: justify;
font-size: 350%;
width: 850px;
}
span {
margin: 0;
padding: 0;
background: black;
color: white;
}
JavaScript
const p = document.querySelector('p');
const shouldWrap = document.querySelector('input');
const range = document.createRange();
const btn = document.querySelector('button');
let isSplit = false;
let span = document.createElement('span');
btn.addEventListener('click', () => {
if (isSplit) {
let span = document.querySelector('span');
if (span) {
p.replaceChild(span.firstChild, span);
}
p.normalize();
btn.innerHTML = 'Split!';
}
else {
p.firstChild.splitText(38).splitText(27);
if (shouldWrap.checked) {
span.appendChild(p.childNodes[1]);
p.insertBefore(span, p.childNodes[1]);
}
btn.innerHTML = 'Restore!';
}
isSplit = !isSplit;
}, false);