Categories
JavaScript Answers

How to copy text from a div to clipboard with JavaScript?

Spread the love

Sometimes, we want to copy text from a div to clipboard with JavaScript.

In this article, we’ll look at how to copy text from a div to clipboard with JavaScript.

How to copy text from a div to clipboard with JavaScript?

To copy text from a div to clipboard with JavaScript, we can use the document.execCommand method.

For instance, we write

const range = document.createRange();
range.selectNode(document.getElementById("a"));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();

to create the range object with createRange.

Then we call selectNode with the element we want to copy text from.

Next we call removeAllRanges to remove all existing selections.

Then we call addRange to add the new range.

We call execCommand with 'copy' to copy the element’s text into the clipboard.

Finally, we call removeAllRanges to remove the selected text.

Conclusion

To copy text from a div to clipboard with JavaScript, we can use the document.execCommand method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.