JSFiddle - React, Tailwind, and code Playground
HTML
<h1>クリップボードにコピーするテスト</h1>
<p id="targetID">下のボタンを押すと、この文字列がクリップボードにコピーされます!</p>
<button id="btnCopy">copy</button>
JavaScript
document.querySelector('#btnCopy').addEventListener("click", function(){
var element = document.querySelector('#targetID');
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
//console.log('選択された文字列: ', selection.toString());
var succeeded = document.execCommand('copy');
if (succeeded) {
alert('コピーが成功しました!');
} else {
alert('コピーが失敗しました!');
}
selection.removeAllRanges();
});