8
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

Zebra
  • 3,858
  • 9
  • 39
  • 52

1 Answers1

31

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;
}
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • [Identical with Tim's answer](http://stackoverflow.com/a/6668159/1269037) to the question this is a duplicate of. – Dan Dascalescu Jun 01 '15 at 15:17
  • @DanDascalescu: Have you downvoted this because it duplicates an answer of mine from another question? – Tim Down Jun 01 '15 at 21:50
  • @TimDown: yes. I wasted a bit of time comparing this answer with the other one to see if maybe you had made an improvement in one of them. Since the question is a closed dupe, if this were my answer, I'd edit it to link to the answer in the other question, in order to save users some time. (My workflow is that I google for something then open the first few most promising results in different tabs, and compare the solutions.) – Dan Dascalescu Jun 02 '15 at 04:36
  • 3
    @DanDascalescu: OK, fair enough. I have quite a number of duplicate answers on SO from a few years ago when I was rather more ruthless in accumulating reputation than I am now so I will fix them as I see them. – Tim Down Jun 02 '15 at 11:53
  • This still returns only the text and not the HTML node of the current selection. – Siddhant Varma Mar 29 '23 at 05:55
  • @SiddhantVarma: Well, it returns an HTML representation of the current selection as text, which is what the question asked for. There may not be a single DOM node that represents the selection, so what exactly do you require? – Tim Down Mar 31 '23 at 08:56