0

Here's the scenario: The user selects some text. I want to modify the selection to include the complete text inside the bounding AnchorNode and FocusNode, regardless of where the user starts and stops selecting.

<script>
    document.onselectionchange =(e)=>{
        let sel=document.getSelection();
        // Here I want to expand the selection to include all the text in the selection. For example
        // if "AA CC" is selected in the html below, I want to expand it to "AAAA BBBB CCCC"
    }
</script>




<span id="container" contenteditable="true">
    <span id="span1">AAAA </span><span id="span2">BBBB </span><span id="span3">CCCC </span><span id="span4">DDDD</span>
</span>

Is this possible? Any guidance would be appreciated.

Len White
  • 892
  • 13
  • 25

1 Answers1

0

OK, I saw another post on here that clued me into the fact that the secret is in creating a range object. This gives me what I wanted:

    function onMouseUp(e) {
        let sel = document.getSelection();
        if (sel && sel.anchorNode && sel.anchorNode != document & sel.toString() != "") {
            let a = sel.anchorNode;
            let f = sel.focusNode;
            let r = document.createRange();
            r.setStartBefore(a);
            r.setEndAfter(f);
            sel.removeAllRanges();
            sel.addRange(r);
            console.log(sel.toString());
        }
    }
    window.addEventListener("mouseup", onMouseUp);
Len White
  • 892
  • 13
  • 25