select
определяется для текста только в элементе <input>
или <textarea>
. Вы можете создать элемент узла динамически и установить его innerText
со значением кнопки:
for (const elem of document.querySelectorAll(".copy")) {
elem.addEventListener("click", e => {
const ta = document.createElement("textarea");
ta.innerText = e.target.innerText;
document.body.appendChild(ta);
ta.select();
document.execCommand("copy");
document.body.removeChild(ta);
});
}
<button class="copy">Click to copy this text data to clipboard.</button>
<button class="copy">Click to copy this different text data to clipboard.</button>
Существует более элегантный вариант, совместимый с Chrome / FF: Clipboard.writeText
:
for (const elem of document.getElementsByClassName("copy")) {
elem.addEventListener("click", e =>
navigator.clipboard.writeText(e.target.innerText)
);
}
<button class="copy">Click to copy this text data to clipboard.</button>
<button class="copy">Click to copy this different text data to clipboard.</button>