最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

HTML document selection using javascript - Stack Overflow

programmeradmin0浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论