Skip to main content

JavaScript: Select Content and Copy to Clipboard (Snippet)

ℹ️ For Any Element

Applicable for input and textarea elements.

Also general DOM elements:

  • div
  • p
  • blockquote
  • span
  • strong
  • em
  • Et cetera.

🧑‍💻 Snippet


Usage

How to use:

Or use .addEventListener("click", callbackFunction) so we can remove it afterwards with .removeEventListener("click", callbackFunction).

Promise-Based

This snippet is a Promise-based function.

We can put await or attach .then() if there's a follow-up method after the completion.

Example with await

Assuming it's invoked inside an async function or at the top level of a module.

Example with .then()


Selection Method

The selection methods are differentiated to accommodate different types of DOM element.

input and textarea

It is from this part of the script:

  • HTMLInputElement = input element.
  • HTMLTextAreaElement = textarea element.

General DOM Elements

From this part of the script:

Copy Method

This function uses Clipboard API as the substitute for the deprecated document.execCommand() method.

This part of the script:


Thank you for visiting. 👋

Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy