JSFiddle - React, Tailwind, and code Playground

by Anirudh Tewathia

HTML

<div id="replytekst">
    <p>Some text containing <b>HTML</b>, and this div is the only one where we can copy som text from</p>
</div>

<div id="tekst2">
    <p>This is another div tag, and then text in this div must not be copied</p>
</div>
<p>
   <a href="#" id="test">Citér</a>
</p>

JavaScript

function getHTMLOfSelection (argNode) {
  var range;
  if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    return range.htmlText;
  }
  else if (window.getSelection) {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
      range = selection.getRangeAt(0);
      var clonedSelection = range.cloneContents();
      var div = document.createElement('div');
      div.appendChild(clonedSelection);
      			if (selection.baseNode.parentElement.parentElement.id === argNode.getAttribute('id') || selection.baseNode.parentElement.parentElement.parentElement.id === argNode.getAttribute('id')) {
				return div.innerHTML;
			} else {
				return '';
			}
    }
    else {
      return '';
    }
  }
  else {
    return '';
  }
}

$(document).ready(function(){
$("#test").click(function() {
var kopitekst = document.getElementById("replytekst");
var kopitjek=getHTMLOfSelection(kopitekst);
if (kopitjek=='')
  {
alert("Please select some content");
  }
else
  {
alert(kopitjek);
}});
});