Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

DmitryOlkhovoi commented Dec 14, 2013

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

@yattias

This comment has been minimized.

Copy link

yattias commented Oct 17, 2015

Nice work. Simple, but helpful.

@fatso83

This comment has been minimized.

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

This comment has been minimized.

Copy link

jadamconnor commented Apr 30, 2017

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

@serapath

This comment has been minimized.

Copy link

serapath commented Jul 13, 2017

nice :-)

@tannerlyons

This comment has been minimized.

Copy link

tannerlyons commented Jun 10, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.