How to highlight text using javascript

后端 未结 13 2236
名媛妹妹
名媛妹妹 2020-11-22 02:32

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

13条回答
  •  旧巷少年郎
    2020-11-22 03:05

    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

提交回复
热议问题