When I select some text via the window.getSelection().addRange() function just after I edit the element, the selection is not shown on the browser (Chrome). I need it for a search/replace functionality on a website. So when I replace the string in an element and then select the next occurrence it is set correctly, but it is not highlighted.
This is the code (the replace function is called by a click event on a button):
replace(text, value) {
let selection = window.getSelection();
let contentString = selection.focusNode.textContent;
let replaceString = contentString.substring(selection.focusOffset - text.length, selection.focusOffset);
if (replaceString === text) {
selection.focusNode.textContent = contentString.substring(0, selection.focusOffset - text.length) + value + contentString.substring(selection.focusOffset);
}
this.search(text);
//setTimeout(() => this.search(text), 500); //with this it works
}
The search function loops through the elements that should be searched, this is the part where the range gets set:
const range = document.createRange();
range.setStart(foundElement.firstChild, index);
range.setEnd(foundElement.firstChild, index + text.length);
window.getSelection().removeAllRanges();
foundElement.scrollIntoView(false);
window.getSelection().addRange(range);
I put the search function in a timeout and then it worked. So I assume that the element is still edited when the text selection happens, but I don't really understand why the selection works correctly but it is just not highlighted. I can just use the timeout and it would work fine, but it wouldn't be very smooth. Is there another way to get around this?