How to Copy Text from a Paragraph Using JavaScript?

Estimated read time 3 min read

To copy text from a paragraph element using JavaScript, you can use the clipboardData property of the event object, which is available in Internet Explorer, or the Clipboard API, which is available in modern browsers.

Here’s an example of how to copy text from a p element using the clipboardData property:

document.getElementById("copy-button").addEventListener("click", function() {
  var p = document.getElementById("paragraph");
  var text = p.innerText;
  
  document.addEventListener("copy", function(event) {
    event.clipboardData.setData("text/plain", text);
    event.preventDefault();
  });
  
  document.execCommand("copy");
});

In this example, we add an event listener for the click event to a button with an ID of copy-button, and in the event handler, we get a reference to the p element using its ID, and get the text from the p element using the innerText property. Then we add another event listener for the copy event to the document, and in the event handler, we use the setData method of the clipboardData property to set the text from the p element to be copied to the clipboard. We also call the preventDefault method to prevent the default behavior of the copy event. Finally, we call the execCommand method with the "copy" command to initiate the copy action.

Here’s an example of how to copy text from a p element using the Clipboard API:

document.getElementById("copy-button").addEventListener("click", function() {
  var p = document.getElementById("paragraph");
  var text = p.innerText;
  
  navigator.clipboard.writeText(text).then(function() {
    console.log("Text copied to clipboard");
  }, function(err) {
    console.error("Failed to copy text: ", err);
  });
});

In this example, we add an event listener for the click event to a button with an ID of copy-button, and in the event handler, we get a reference to the p element using its ID, and get the text from the p element using the innerText property. Then we use the writeText method of the Clipboard API to write the text from the p element to the clipboard. The method returns a Promise that resolves when the text has been successfully copied to the clipboard, or rejects if there was an error.

Please note that due to security and privacy concerns, the ability to copy text from the clipboard is typically restricted in web browsers. You may need to request permission from the user to copy text from the clipboard, and you should also provide a user interface, such as a button, to initiate the copy action.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply