Skip to content

Instantly share code, notes, and snippets.

@ssokolow
Created June 25, 2009 03:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssokolow/135661 to your computer and use it in GitHub Desktop.
Save ssokolow/135661 to your computer and use it in GitHub Desktop.
How to get the current selection in HTML rather than plaintext
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