I am looking for a way to dynamically change the appearance of a specific word within an HTML paragraph
let textToFind = "testing"
let beforeNode = document.createElement('p');
let afterNode = document.createElement('p');
let highlightedSpan = document.createElement('span')
highlightedSpan.innerHTML = textToFind;
highlightedSpan.style.backgroundColor = "yellow"
let newPar = document.createElement('p');
newPar.appendChild(highlightedSpan);
document.querySelectorAll('p').forEach((par) => {
let content = par.textContent;
let startPos = content.indexOf(textToFind)
console.log(startPos)
if (startPos !== -1) {
let firstPart = content.slice(0, startPos - 1)
let thirdPart = content.slice(startPos + textToFind.length, content.length - 1)
beforeNode.appendChild(document.createTextNode(firstPart))
afterNode.appendChild(document.createTextNode(thirdPart))
par.replaceWith(beforeNode, highlightedSpan, afterNode)
}
})
<p> A complete text for testing purposes</p>
This currently gives me the following result:
https://i.sstatic.net/wK52a.png
However, I am seeking a more visually appealing approach as the current implementation splits the text into three lines. Is there a neater solution to changing the style of a single word in an HTML paragraph?