js copy span to clipboard code example

Example 1: js copy span text to clipboard

document.getElementById("cp_btn").addEventListener("click", copy_password);

function copy_password() {
    var copyText = document.getElementById("pwd_spn");
    var textArea = document.createElement("textarea");
    textArea.value = copyText.textContent;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("Copy");
    textArea.remove();
}

Example 2: copy clipboard with span

<span id="to-select-text">1111 - 2222 - 3333 - 4444</span>
<button id="copy-button">Copy</button>