Javascript - Copy content from a <span> to clipboard by clicking a <button>

Asked

Viewed 698 times

4

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

inserir a descrição da imagem aqui

Example HTML code:

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

Note: Pure Javascript.

  • Nothing to do, kkkkkk...

  • 1

    console.log(document.getElementById('numerosx').innerHTML) resolves?

  • I didn’t understand well, kkkkk, you could answer :) I’m not very good with JS.

  • @rray responds there :)

  • 1

    Is that what you wanted? by the question implied something else.

1 answer

4


Behold:

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>

  • Friend, it is functional, but when I put it here it didn’t work. I put it exactly as you answered. Is it something you forgot? I don’t know much about JS...

  • Yes, it works well. It’s not working on my site. Rsrsrs, I think you might be having trouble with another external script. You don’t know how to "force" it? :(

  • Yes, I think it won’t work on the page I have here no.

  • I don’t know, there’s something that’s blocking, it must be coming from external scripts, so I don’t know how to make it work :(

  • Only if I had something to make it work :(

  • Here it didn’t work...

  • @Matheusvitor has succeeded?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.