0

I am trying to copy contents of a span element but I failed so far with no error in chrome:

const element = document.getElementById("element");
 console.log(element.innerHTML); //consoles Data
 //below doesn't copy contents of the element to clipboard
 const node = document.createRange();
 node.selectNode(element);
 window.getSelection().removeAllRanges();
 window.getSelection().addRange(node);
 document.execCommand("copy");
 <span id="element">Data</span>

Since I can see contents of the element via innerHTML, I am thinking the element is indeed accessible. Why cant I copy the text?

ccarstens
  • 419
  • 3
  • 13
Wede Asmera Tseada
  • 513
  • 2
  • 4
  • 14

2 Answers2

0

This answers your questions:

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();
}
<span id="pwd_spn" class="password-span">Test</span>
<button id="cp_btn">Copy</button>
ccarstens
  • 419
  • 3
  • 13
0

The only thing that is wrong in your code is that there is no button. It is impossible to copy text without one, in order to prevent clipboard poisoning. The following should work for you:

function copy() { 
   const element = document.getElementById("element");
   const node = document.createRange();
   node.selectNode(element);
   window.getSelection().removeAllRanges();
   window.getSelection().addRange(node);
   document.execCommand("copy");
}
<span id="element">Data</span>
<button onclick="copy()">Copy</button>

However, I think that a simpler way to achieve the same thing is this (Copy text from <span> to clipboard):

function copy() {
    var copyText = document.getElementById("element");
    var textArea = document.createElement("textarea");
    textArea.value = copyText.textContent;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("Copy");
    textArea.remove();
}
<span id="element">Data</span>
<button onclick="copy()">Copy</button>
Diogenis Siganos
  • 779
  • 7
  • 17