Open In App
Related Articles

How to copy the text to the clipboard in JavaScript ?

Improve Article
Save Article
Like Article

In order to copy the text to the clipboard in JavaScript we use document.execCommand() method. This can be done by following the below-mentioned approach.


The JavaScript code will look like this:

function GeeksForGeeks() {
    /* Get the text field */
    let copyGfGText = document.getElementById("IdOfTextToCopy");
    /* Select the text field */;
    /* Copy the text inside the text field */
    /* Use below command to access the 
       value of copied text */

Note: The document.execCommand() method is not supported in IE8 and earlier. 

Example: In this example, we will apply the above approach.


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
        How to copy the text to the
        clipboard in JavaScript ?
    <h1 style="color:green;">
    <input type="text" value="GeeksForGeeks"
    <button onclick="GeeksForGeeks()">
        Copy text
        Click on the button to copy the text
        from the text field.<br> Try to paste
        the text (e.g. ctrl+v) afterwards in
        a different window, to see the effect.
    <p id="gfg"></p>
        function GeeksForGeeks() {
            let copyGfGText =
                .innerHTML = "Copied the text: "
                + copyGfGText.value;


How to copy the text to the clipboard in JavaScript?

How to copy the text to the clipboard in JavaScript?

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 08 Jun, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials