I just recently needed to get the actual HTML of what was selected in a browser. Selected as in “you drag your mouse across some text and it turns blue”. So I came up with this nifty piece of JavaScript code that works quite flawlessly across all major browsers (yes, including IE).
/**
* gets the current selection, including HTML code
* @return string
*/
function getSelectionHTML() {
var userSelection;
try {
if (window.getSelection) {
// W3C ranges
userSelection = window.getSelection();
if (userSelection.getRangeAt)
var range = userSelection.getRangeAt(0);
else {
var range = document.createRange();
range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
var clonedSelection = range.cloneContents();
var div = document.createElement("div");
div.appendChild(clonedSelection);
return div.innerHTML;
} else if (document.selection) {
// Internet Explorer selection
userSelection = document.selection.createRange();
return userSelection.htmlText;
} else {
return "";
}
} catch(e) {
// an error occurred - supposedly nothing is selected
return "";
}
};