Selecting text in an element (akin to highlighting with your mouse)

后端 未结 16 1621
孤街浪徒
孤街浪徒 2020-11-21 05:58

I would like to have users click a link, then it selects the HTML text in another element (not an input).

By \"select\" I mean the same way you would select

16条回答
  •  余生分开走
    2020-11-21 06:13

    My particular use-case was selecting a text range inside an editable span element, which, as far as I could see, is not described in any of the answers here.

    The main difference is that you have to pass a node of type Text to the Range object, as described in the documentation of Range.setStart():

    If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.

    The Text node is the first child node of a span element, so to get it, access childNodes[0] of the span element. The rest is the same as in most other answers.

    Here a code example:

    var startIndex = 1;
    var endIndex = 5;
    var element = document.getElementById("spanId");
    var textNode = element.childNodes[0];
    
    var range = document.createRange();
    range.setStart(textNode, startIndex);
    range.setEnd(textNode, endIndex);
    
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    

    Other relevant documentation:
    Range
    Selection
    Document.createRange()
    Window.getSelection()

提交回复
热议问题