Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
Niraj Choubey Avatar asked Apr 14 '11 20:04

Niraj Choubey


People also ask

How do I get text in a div?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants.

How do I get selected text Contenteditable?

text) { return selection. text; } return false; } return false; }; $("#content-create-partial"). bind("mouseup", function(){ var text = getSelected(); if(text) { console. log(text); } else{ console.


1 Answers

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;
}
like image 66
Tim Down Avatar answered Oct 06 '22 10:10

Tim Down