Javascript - Copy content from a span to clipboard by clicking a button [duplicate]

4
  

I am creating a CPF generator, which when the person generates, a "Copy" option appears, but I would like to know how to implement the copying of the content that is displayed.

ExampleHTMLCode:

<spanid="numerosx">56262662</span>
<button id="btcopiar">COPIAR</button>

Note: Pure Javascript.

    
asked by anonymous 16.08.2016 / 09:14

1 answer

4

See:

document.querySelector("button").onclick = function() {
    var element= document.getElementById('numerosx');
    var range = document.createRange();
    range.selectNode(element);
    window.getSelection().addRange(range);
    document.execCommand("copy");
};
<span id="numerosx">56262662</span>
<button id="btcopiar">COPIAR</button>
    
16.08.2016 / 14:06