Created
June 25, 2009 03:09
-
-
Save ssokolow/135661 to your computer and use it in GitHub Desktop.
How to get the current selection in HTML rather than plaintext
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
getSelectionHTML = -> | |
# Everyone but IE supports DOM selections | |
if window.getSelection | |
sel = window.getSelection() | |
# IE Selections (Must come last to avoid messing with Opera) | |
else if document.selection | |
return document.selection.createRange().htmlText | |
# Fail safely | |
else | |
return "" | |
if sel.getRangeAt | |
# Everything but IE and old Safari | |
range = sel.getRangeAt(0) | |
else | |
# Old Safari | |
range = document.createRange() | |
range.setStart(sel.anchorNode, sel.anchorOffset) | |
range.setEnd(sel.focusNode, sel.focusOffset) | |
# Convert the document fragment to a string | |
div = document.createElement('div') | |
div.appendChild(range.cloneContents()) | |
return div.innerHTML | |
# For those of you who can't readily compile CoffeeScript into Javascript, | |
# 1. Visit http://jashkenas.github.com/coffee-script/ | |
# 2. Click "Try CoffeeScript" and paste this into the left-hand pane | |
# 3. Copy the result from the right-hand pane. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment