javascripthighlightselection-api

how to get span selected portion using Javascript


is there a way to get the highlighted selectionstart and selectedlenght on a span ?

Thanks


Solution

  • I use my own optimization of the algorithms in IERange, which provides a wrapper around IE's TextRange (which is what you get from the selection in IE) to give them the same interface as DOM Ranges.

    To get the selection in the document, use something like the following:

    var sel = window.getSelection(); // Provided by IERange in IE, built-in in other browsers
    var range = sel.getRangeAt(0); // Note this doesn't work in Safari 2
    

    range now has properties startContainer and startOffset, which are respectively a reference to a node and an offset within that node that represent the start of the selection, and corresponding properties endContainer and endOffset that represent the end of the selection.