JSFiddle - React, Tailwind, and code Playground
HTML
click the bold line and press ctrl+c (win) or cmd+c (mac)<br><br>
<div id='myDiv'><b>some bold text</b>
CSS
div.content {
all: default;
}
JavaScript
document.getElementById('myDiv').addEventListener('copy', onCopyEvent);
function onCopyEvent(e) {
e.preventDefault();
copyHtmlToClipboard(e.target.outerHTML); // html
}
function copyHtmlToClipboard(html) {
var div = document.createElement("div");
div.style.opacity = 0;
div.style.position = "absolute";
div.style.pointerEvents = "none";
div.style.zIndex = -1;
div.setAttribute('tabindex', '-1'); // so it can be focused
div.innerHTML = html;
document.body.appendChild(div);
var focused=document.activeElement;
div.focus();
window.getSelection().removeAllRanges();
var range = document.createRange();
// not using range.selectNode(div) as that makes chrome add an extra <br>
range.setStartBefore(div.firstChild);
range.setEndAfter(div.lastChild);
//range.selectNode(div);
window.getSelection().addRange(range);
var ok=false;
try {
ok = document.execCommand('copy');
} catch (err) {
console.log(err);
}
if (!ok) console.log('execCommand failed!');
window.getSelection().removeAllRanges();
document.body.removeChild(div);
focused.focus();
}