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;
@DmitryOlkhovoi
Copy link

it's ridiculous. I use script text/template for my erb

@yattias
Copy link

yattias commented Oct 17, 2015

Nice work. Simple, but helpful.

@fatso83
Copy link

fatso83 commented Feb 6, 2017

Great snippet. I suspect Dmitry had no idea what you were trying to show, and thought you were doing this as an alternative to templating languages.

@jadamconnor
Copy link

It seems like every few years someone comes along to commend this snippet. I guess I'm next. Great snippet!

@serapath
Copy link

nice :-)

@tannerlyons
Copy link

Whoops we missed 2018. So I'll leave an extra exclamation mark in lieu:
nice!!

@lebesnec
Copy link

lebesnec commented Apr 9, 2020

no idea how I ended up here but I guess I have to leave a comment for 2020 !

@injune1123
Copy link

It's priceless even in 2020. Thank you!

@picos77
Copy link

picos77 commented Jul 24, 2021

Before, to get string from documentFragment, I did this way :

var map = Array.prototype.map;
return map.call( fragment.childNodes, function(x){ return x.nodeType === x.TEXT_NODE ? x.textContent : x.outerHTML } ).join("");

But your your way is obviously much more elegant and so simple !

So, now I do this way :
var div = document.createElement('div');
div.appendChild( fragment.cloneNode(true) );
return div.innerHTML;

It's almost too easy ... thank you !

@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