Skip to content

Instantly share code, notes, and snippets.

@kharmabum
Created July 24, 2013 21:49
Show Gist options
  • Save kharmabum/6074896 to your computer and use it in GitHub Desktop.
Save kharmabum/6074896 to your computer and use it in GitHub Desktop.
Get selected text from the browswer window
selectedText: function() {
var html = '';
if (typeof window.getSelection !== "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection !== "undefined") {
if (document.selection.type === "Text") {
html = document.selection.createRange().htmlText;
}
}
// Strip out any .click elements from the HTML before converting it to text
var div = document.createElement('div');
div.innerHTML = html;
$('.clicks', $(div)).remove();
var text = div.textContent || div.innerText || "";
return String(text).trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment