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

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.