-
-
Save hthuong09/7e10957df5bdd5ef2e354aa5334c4e42 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment