petermac-
4/24/2012 - 2:58 AM

Javascript documentfragment to string (w/ text selection)

Javascript documentfragment to string (w/ text selection)

// selection range
var range = window.getSelection().getRangeAt(0);

// plain text of selected range (if you want it w/o html)
var text = window.getSelection();
    
// document fragment with html for selection
var fragment = range.cloneContents();

// make new element, insert document fragment, then get innerHTML!
var div = document.createElement('div');
div.appendChild( fragment.cloneNode(true) );

// your document fragment to a string (w/ html)! (yay!)
var html = div.innerHTML;