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)

1
  • Offset from the beginning of what? Commented Oct 11, 2010 at 11:11

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

5 Comments

so this code copies the selection into a new div, then counts the length of its innerHtml?
In non-IE browsers, yes, exactly.
what about the offset from the beginning of the parent element? thanks
I'm interested in the answer to rana's question, too.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.