I created a custom function to emphasize specific strings within a text by surrounding them with span
tags and updating the content using the innerHTML
property of the targeted element.
However, I encountered an issue while working with innerHTML
instead of innerText
. If the string to be replaced contains a character that is part of the span
tag, it also gets replaced, resulting in a messy output.
Let me illustrate this problem with an example showcasing my function:
const strings = ['e', 'a'];
const pElement = document.querySelector('p');
function highlight(strings) {
var highlightedText = pElement.innerText
strings.forEach(element => {
if (pElement.innerHTML.includes(`<span class="span">${element.charAt(0)}</span>`) && element.length > 1)
highlightedText = highlightedText.replaceAll(`<span class="highlight">${element.charAt(0)}</span>`, element)
//in case string element from array is longer than 1, so not important in this example
if (pElement.innerText.includes(element))
highlightedText = highlightedText.replaceAll(element, `<span class="highlight">${element}</span>`)
});
pElement.innerHTML = highlightedText
}
highlight(strings)
.highlight {
background-color: red
}
<p>Lorem ipsum dolor sit amet</p>
As demonstrated above, when running the function, the output becomes:
Loran class="highlight">ean>m ipsum dolor sit aman class="highlight">ean>t
, due to the unintended replacement of characters within the span
tags.
If anyone has a suggestion on how to only update the characters within the text without affecting the HTML elements, I would greatly appreciate it.