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.createRange().

But, how can i find selected text html in FireFox. How can in do this.Please help.

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/


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;
}

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


to get the text of a div you do this:(in jQuery)

var text = $('div.selector').text();