Skip to content

Instantly share code, notes, and snippets.

@gleuch
Created April 24, 2012 02:58
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save gleuch/2475825 to your computer and use it in GitHub Desktop.
Save gleuch/2475825 to your computer and use it in GitHub Desktop.
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;
@MatthieuOlague
Copy link

This post is gold, thank you everyone! Whish you a happy 2023.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment