Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of
Fast forward to 2019, Web API now has natively support for highlighting texts:
const selection = document.getSelection();
selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
And you are good to go! anchorNode
is the selection starting node, focusNode
is the selection ending node. And, if they are text nodes, offset
is the index of the starting and ending character in the respective nodes. Here is the documentation
They even have a live demo