get selected text's html in div
i have a div with contentEditable set to true. I have to find selected text html.I am able to get selected text in FireFox by
window.getSelection();
I case of IE i am able to get selected text html by using
document.selection.create开发者_如何学PythonRange().
But, how can i find selected text html in FireFox. How can in do this.Please help.
To get the selected HTML as a string, you can use the following function:
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
Select text and store it in variable called mytext
.
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
$(function() {
$(document).bind("mouseup", function() {
var mytext = x.Selector.getSelected();
alert(mytext);
});
});
Check working example at http://jsfiddle.net/YstZn/1/
window.getSelection().getRangeAt(0);
It returns a document fragment. It contains the nodes where the selection begins and ends and some other juicy stuff. Inspect it with FireBug or another JavaScript console, &&|| for more info
- https://developer.mozilla.org/en/DOM/Selection
- https://developer.mozilla.org/en/DOM/range
- https://developer.mozilla.org/en/window.getSelection
According to MDN:
"A Selection object, when cast to string, either by appending an empty string ("") or using Selection.toString(), returns the text selected."
For me, any of the following work in Chrome 86:
String(window.getSelection())
window.getSelection() + ""
window.getSelection().toString()
String(document.getSelection())
document.getSelection() + ""
document.getSelection().toString()
https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
to get the text of a div you do this:(in jQuery)
var text = $('div.selector').text();
精彩评论