window.getSelection return html

Zebra picture Zebra · Mar 7, 2011 · Viewed 16.5k times · Source
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

Answer

Tim Down picture Tim Down · Mar 7, 2011

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