views:

39

answers:

1

I use this javascript code to get the currently highlighted selection.

var selection = window.getSelection()

If the highlight is a section of text all within a <div>, how can I get the offset from the beginning of the <div> and the length of the highlight? (the length is not just the length of the text, it should be the actual length of the html code for that text)

+3  A: 

You can get the length of the selected HTML as follows:

function getSelectionHtml() {
    var sel, html = "";
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            var frag = sel.getRangeAt(0).cloneContents();
            var el = document.createElement("div");
            el.appendChild(frag);
            html = el.innerHTML;
        }
    } else if (document.selection && document.selection.type == "Text") {
        html = document.selection.createRange().htmlText;
    }
    return html;
}

alert(getSelectionHtml().length);
Tim Down
so this code copies the selection into a new div, then counts the length of its innerHtml?
Rana
In non-IE browsers, yes, exactly.
Tim Down
what about the offset from the beginning of the parent element? thanks
Rana
I'm interested in the answer to rana's question, too.
Tom
Such an offset is unlikely to be useful and difficult to obtain. What's wrong with the offset you get from a Range obtained from the selection?
Tim Down