How to Copy HTML to the Clipboard Using JavaScript?

Estimated read time 2 min read

You can use the clipboardData object and its setData method to copy HTML content to the clipboard in JavaScript. Here’s an example:

HTML:

<div id="textToCopy">This is some HTML content to copy.</div>
<button id="copyButton">Copy</button>

JavaScript:

const textToCopy = document.getElementById("textToCopy");
const copyButton = document.getElementById("copyButton");

copyButton.addEventListener("click", function() {
  const selection = window.getSelection();
  const range = document.createRange();
  range.selectNodeContents(textToCopy);
  selection.removeAllRanges();
  selection.addRange(range);

  try {
    document.execCommand("copy");
    console.log("HTML content copied to clipboard.");
  } catch (err) {
    console.error("Failed to copy HTML content to clipboard.", err);
  }

  selection.removeAllRanges();
});

In this example, the HTML content to be copied is inside a div element with id “textToCopy”. The button with id “copyButton” is used to trigger the copy action.

When the button is clicked, the addEventListener method is used to register a click event listener on the button. The function inside the addEventListener method selects the HTML content inside the “textToCopy” element, creates a selection range, adds it to the selection, and then executes the “copy” command using document.execCommand("copy").

Note that the execCommand method is an old method and may not work in all modern browsers. A more modern and reliable way to copy content to the clipboard is to use the Clipboard API, which is supported in recent versions of most browsers. Here’s an example:

const textToCopy = document.getElementById("textToCopy");
const copyButton = document.getElementById("copyButton");

copyButton.addEventListener("click", function() {
  navigator.clipboard.writeText(textToCopy.innerHTML).then(function() {
    console.log("HTML content copied to clipboard.");
  }, function(err) {
    console.error("Failed to copy HTML content to clipboard.", err);
  });
});

In this example, the navigator.clipboard.writeText method is used to write the HTML content inside the “textToCopy” element to the clipboard as plain text. The method returns a Promise that resolves if the content was successfully copied, or rejects if an error occurred.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply