I am trying to insert a new span into a paragraph that already has spans. If the paragraph doesn’t have any spans the inserting of the new span works perfectly.
But it gets messed up when one or more spans already exists in the paragraph. Is it even possible to make this work?
At the last 3 lines of the function is where the paragraph gets put back together to insert the new span in between. I am having trouble converting the split paragraph back into a HTML format, it always seems to stay like a string or something else is getting in the way. You can get an idea by running the code and selecting some text, it will insert the span at the mouseup event.
function replaceSelectedParagraphTextBySpan() {
// get range and text of selected text in paragraph
let text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
const storedSelections = []
const currSelection = window.getSelection();
for (let i = 0; i < currSelection.rangeCount; i++) {
storedSelections.push(currSelection.getRangeAt(i))
}
const rangeStart = storedSelections[0].startOffset
const rangeEnd = storedSelections[0].endOffset
// our paragraph
const textObject = document.getElementById('textObject')
const frontParagraph = textObject.innerHTML.substring(0, rangeStart)
const backParagraph = textObject.innerHTML.substring(rangeEnd, textObject.length)
// I tried here to convert the front and backParagraph into a paragraph element because instead it
// just remains a string
const pElementFront = document.createElement('p').innerHTML = frontParagraph
const pElementBack = document.createElement('p').innerHTML = backParagraph
// create our span for inserting
const span = document.createElement('span')
span.innerHTML = " <this text got added> "
// insert new span into paragraph at selected range
textObject.innerHTML = pElementFront
textObject.appendChild(span)
textObject.innerHTML = textObject.innerHTML + pElementBack
}
const paragraph = document.getElementById('textObject')
paragraph.addEventListener('mouseup', e => {
replaceSelectedParagraphTextBySpan()
})
<p id="textObject"><span>Select some </span>text and the selected text will get replaced by a span</p>