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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *