admin管理员组

文章数量:1415484

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)

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)

Share Improve this question edited Oct 11, 2010 at 11:15 Andrzej Doyle 104k33 gold badges191 silver badges231 bronze badges asked Oct 11, 2010 at 11:06 RanaRana 4,6219 gold badges33 silver badges39 bronze badges 1
  • Offset from the beginning of what? – Tim Down Commented Oct 11, 2010 at 11:11
Add a ment  | 

1 Answer 1

Reset to default 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);

本文标签: HTML document selection using javascriptStack Overflow