HTML document selection using javascript
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 开发者_JAVA百科should be the actual length of the html code for that text)
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);
精彩评论