Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.getSelection return html [duplicate]

function selected() {
   var selObj = window.getSelection();
}


This function returns selected text from a webpage. How do return the html of a selected area. Is this possible to do with an <img> and an <a> tag?


Here's the list of functions:
https://developer.mozilla.org/Special:Tags?tag=DOM&language=en

like image 438
Zebra Avatar asked Mar 07 '11 17:03

Zebra


1 Answers

The following will do this in all major browsers and is an exact duplicate of this answer:

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 58
Tim Down Avatar answered Sep 27 '22 19:09

Tim Down