28

Is there a cross-browser way to get HTML of selected text?

7

2 Answers 2

50

This function will do it in all major browsers:

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


// bind events for selection

document.addEventListener('mouseup', function(){
  var selectedHTML = getSelectionHtml();
  if( selectedHTML )
    console.log( selectedHTML )
});

document.addEventListener('keyup', function(e){ 
  var selectedHTML, key = e.keyCode || e.which; 
  if( key == 16 ){ // if "shift" key was released
    selectedHTML = getSelectionHtml();
    if( selectedHTML )
      console.log( selectedHTML )
  }
});
<ul contenteditable>
  <li><p>Select <b>this</b> <em>text</em> right <i>here</i></p></li>
  <li>Or <b>this text</b></li>
</ul>

3
  • 3
    The problem with this solution is that when you select the caps-locked part of <p>first paragraph TEXT TO</p><p>BE SELECTED second paragraph</p> you don't get expected "TEXT TO</p><p>BE SELECTED" but "<p>TEXT TO</p><p>BE SELECTED</p> - for some reason browser ads tags that are not in the selection in order to close the ones that are. Is there any way how to get only what really is in the selection?
    – HonzaBé
    Aug 8, 2015 at 6:19
  • 3
    An HTML document is fundamentally a tree of nodes. Once the initial HTML text has been parsed, it's essentially gone and you have to deal in nodes. It would be possible (but relatively complicated) to convert the selection into the kind of string you suggest but there's no guarantee it would match the original HTML text, which is just one of many equally valid ways of representing the document.
    – Tim Down
    Aug 10, 2015 at 8:50
  • I actually want the behavior that @honzzz don't But I am getting what he wants. <p>first paragraph TEXT TO</p><p>BE SELECTED second paragraph</p> shall be returning <p>TEXT TO</p><p>BE SELECTED</p> rather than TEXT TO</p><p>BE SELECTED
    – Stotra
    May 25, 2022 at 18:24
0

If you just need the text of the selection, use .toString():

window.getSelection()?.toString()
'Is there a cross-browser way to get HTML of selected text?'
1
  • it's giving raw text (inner text)
    – Dan D.
    Feb 4 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.