title: Copy rich text to clipboard with styles from css-classes
body: <p>I've used <a href="https://stackoverflow.com/questions/23934656/javascript-copy-rich-text-contents-to-clipboard">this method</a> to copy rich text from an html element. The problem is that if styles are not inlined in the html, but come from css, this method doesn't work. The existing code breaks the formatting and doesn't take the styles into account. Here's the code.</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;button onclick="copyToClip(document.getElementById('foo').innerHTML)"&gt;
    Copy the stuff
    &lt;/button&gt;
  
  &lt;div id=foo&gt;
    You can write some JS to generate this data. 
    It can contain rich stuff.
    &lt;b&gt; test &lt;/b&gt; me &lt;i&gt; also &lt;/i&gt;
    &lt;div class="green"&gt;Hello world&lt;/div&gt; 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
    &lt;ul&gt;
      &lt;li&gt;plain text editor&lt;/li&gt;
      &lt;li&gt;or into a rich text editor&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>CSS</strong></p>
  
  <pre><code>.green {
    display: inline;
    color: green;
  }
  </code></pre>
  
  <p><strong>JavaScript</strong></p>
  
  <pre><code>function copyToClip(str) {
    function listener(e) {
      e.clipboardData.setData("text/html", str);
      e.clipboardData.setData("text/plain", str);
      e.preventDefault();
    }
    document.addEventListener("copy", listener);
    document.execCommand("copy");
    document.removeEventListener("copy", listener);
  };
  </code></pre>
  
  <p>The example <a href="https://codepen.io/evb0110/pen/dLyOPb" rel="nofollow noreferrer">in Codepen</a>.</p>