How to copy text from a div to clipboard in JavaScript

function copyToClip(str) {
  function listener(e) {
    e.clipboardData.setData("text/html", str);
    e.clipboardData.setData("text/plain", str);
  document.addEventListener("copy", listener);
  document.removeEventListener("copy", listener);

var button = document.getElementById('btn');
var div = document.getElementById('foo').innerHTML;

button.addEventListener('click', function() {
<button id="btn">
  Copy the stuff
<div id=foo style="display:none">
  This is some data that is not visible. 
  You can write some JS to generate this data. 
  It can contain rich stuff.
  <b> test </b> me <i> also </i>
  <span style="font: 12px consolas; color: green;">Hello world</span> You can use setData to put TWO COPIES into the same clipboard, one that is plain and one that is rich. That way your users can paste into either a
    <li>plain text editor</li>
    <li>or into a rich text editor</li>
  <textarea placeholder="CTRL+V" rows="5" style="width: 100%"></textarea>
add comment
Suggest a different solution or add another example