Search code examples
javascriptgetselection

How to get selected html text with javascript?


I can use the following code to get selected text:

text=window.getSelection(); /// for Firefox text=document.selection.createRange().text; /// for IE

But how can I get the selected Html, which includes the text and html tags?


Solution

  • In IE <= 10 browsers, it's:

    document.selection.createRange().htmlText
    

    As @DarrenMB pointed out IE11 no longer supports this. See this answer for reference.


    In non-IE browsers, I just tried playing with this... this seems to work, WILL have side effects from breaking nodes in half and creating an extra span, but it's a starting point:

    var range = window.getSelection().getRangeAt(0),
      content = range.extractContents(),
         span = document.createElement('SPAN');
    
    span.appendChild(content);
    var htmlContent = span.innerHTML;
    
    range.insertNode(span);
    
    alert(htmlContent);
    

    Unfortunately, I can't seem to put the node back as it was (since you can be pulling half the text from a span, for instance).