JSFiddle - React, Tailwind, and code Playground

by juErik

HTML

<button id="foo">Copy</button>

JavaScript

function html2clipboard(html, el) {
    var tmpEl;
    if (typeof el !== "undefined") {
        // you may want some specific styling for your content - then provide a custom DOM node with classes, inline styles or whatever you want
        tmpEl = el;
    } else {
        // else we'll just create one
        tmpEl = document.createElement("div");

        // since we remove the element immedeately we'd actually not have to style it - but IE 11 prompts us to confirm the clipboard interaction and until you click the confirm button, the element would show. so: still extra stuff for IE, as usual.
        tmpEl.style.opacity = 0;
        tmpEl.style.position = "absolute";
        tmpEl.style.pointerEvents = "none";
        tmpEl.style.zIndex = -1;
    }

    // fill it with your HTML
    tmpEl.innerHTML = html;

    // append the temporary node to the DOM
    document.body.appendChild(tmpEl);

    // select the newly added node
    var range = document.createRange();
    range.selectNode(tmpEl);
    window.getSelection().addRange(range);

    // copy
    document.execCommand("copy");

    // and remove the element immediately
    document.body.removeChild(tmpEl);
}

document.getElementById("foo").addEventListener("click", function () {
    html2clipboard("My <b>bold</b> text");
});