Skip to content

Instantly share code, notes, and snippets.

@tonioriol
Created February 25, 2018 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonioriol/17d2d1466f52f2acb9c6a6c337159783 to your computer and use it in GitHub Desktop.
Save tonioriol/17d2d1466f52f2acb9c6a6c337159783 to your computer and use it in GitHub Desktop.
Get selected HTML
<!DOCTYPE html>
<html>
<head>
<title>Get selected HTML</title>
<script>
function getSelectionHtml () {
var div, range, sel, result;
if (window.getSelection) {
sel = window.getSelection();
} else if (document.selection) {
result = document.selection.createRange().htmlText;
} else {
result = "";
}
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
} else {
range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
}
div = document.createElement('div');
div.appendChild(range.cloneContents());
result = div.innerHTML;
alert('hola ' + result);
}
</script>
</head>
<body>
<button onclick="getSelectionHtml();">Get</button>
<div>hola1234567890</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment