0

I'm using window.getSelection().anchorOffset and focusOffset to turn selected area into an element. It works fine the first time. But then the parent element divided by new element and getSelection() start count from new element. I don't know how to get current element of getSelection(), this is the only way I can think of to fix this.

var temp = window.getSelection();
    if (temp.anchorOffset < temp.focusOffset) {
        var start = temp.anchorOffset;
        var end = temp.focusOffset;
    }else{
        var end = temp.anchorOffset;
        var start = temp.focusOffset;
    }

    var mid = text.substring(start,end);

    $(".main-element").html(text.substring(0,start)+"<b>"+mid+"</b>"+ text.substring(end));
});
Mido
  • 341
  • 2
  • 15
  • 1
    Both `anchorOffset` and `focusOffset` can be the number of child nodes not just the number of characters which means that your solution will fail if `anchorNode` and `focusNode` are not both text nodes. You can find out more about this from the [DOCUMENTATION](https://developer.mozilla.org/en-US/docs/Web/API/Selection). – Titus Nov 21 '19 at 19:21
  • @Titus This is exactly what I was looking for. More than that, it's a much better way. Thanks you very much. – Mido Nov 21 '19 at 19:31

0 Answers0