JSFiddle - React, Tailwind, and code Playground

by Shital Agarwal

HTML

<h1>Select This</h1>
<div class="article">
<div> div1: This <span>highlighted</span> can be selected.</div>
<div class="unselectable"><br/></div>
<div>div2: And this can again.</div>
</div>

<h1>Output</h1>
<div>
  From: <span id="from"></span>, To: <span id="to"></span>
</div>
<pre id="out">
</pre>

CSS

.unselectable {
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}

pre, .article {
  border: solid 1px black;
  padding: 12px;
}

JavaScript

var onSelect = function(){
  var sel = getSelectionHtml();
  var text = sel.toString();
  console.log(text.toString().split('\n').join(""))
  $('#out').text(text);
}
function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
    alert("heer");
        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;
            /* console.log(container.innerText) */
        }
    } else if (typeof document.selection != "undefined") {
        alert("doc");
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    var $selection = $('<div/>').html(html);
    $selection.find('.unselectable').remove();
    return $selection.text();
}

$('.article').mouseup(onSelect);
$('.article').focusout(onSelect);