Copy and paste

Copy selected text from dom functionality

by Rayudu Ikkurthi

HTML

<table id="textToCopy">
  <tr>
    <td>Vallabha</td>
    <td>Tesing</td>
  </tr>
   <tr>
    <td>Rayudu</td>
    <td>Tesing</td>
  </tr>
</table>
<button id="copyTrigger">Copy above text</button>
<textarea placeholder="Try pasting here to test"></textarea>

CSS

textarea {display: block; margin-top: 1em; width: 500px;}

JavaScript

function doCopy() {
    var textToCopy = document.getElementById('textToCopy');
    var range = document.createRange();
    range.selectNodeContents(textToCopy);
    window.getSelection().addRange(range);
    document.execCommand('copy');
}

(function() {
    var el = document.getElementById("copyTrigger");
    el.addEventListener("click", doCopy, false);
})();