Created
April 24, 2012 02:58
-
-
Save gleuch/2475825 to your computer and use it in GitHub Desktop.
Javascript documentfragment to string (w/ text selection)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
It's priceless even in 2020. Thank you!
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 !
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
no idea how I ended up here but I guess I have to leave a comment for 2020 !