Get selected html text in div
I have a div with contentEditable set to true. I need to find the selected html text. I can get selected text in FireFox on
window.getSelection();
In IE case, I can get the selected html text with
document.selection.createRange().
But how can I find the selected html text in FireFox. How to do it. Help.
+13
source to share
4 answers
Select the text and save it in a 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 out a working example http://jsfiddle.net/YstZn/1/
+12
source to share
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;
}
+16
source to share