Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy text to clipboard from div with javascript

I'm trying to copy the text from the next div to the clipboard with Javascript. Below is my current code:

HTML:

<div class="hl7MsgBox">
    <span class="boxspan">1</span>
    <br>
    <span class="boxspan">2</span>
    <br>
    <span class="boxspan">3</span>
    <br>
    <span class="boxspan">4</span>
    <br>
    <span class="boxspan">5</span>
    <br>
    <span class="boxspan">6</span>
    <br>
    <span class="boxspan">7</span>
    <br>
    <span class="boxspan">8</span>
</div>

Javascript:

$(".btnFileCopy").click(function () {
    var copyText = document.getElementsByClassName("hl7MsgBox");
    copyText.select();
    document.execCommand("copy");
});

I'm expecting to get the new output when I paste it into the notepad:

1
2
3
4
5
6
7
8

However, for some reason, it's not working and throw the next error message :

Uncaught TypeError: copyText.select is not a function ...

Does anyone know how could I solve this issue?

like image 454
Jin Yong Avatar asked Dec 05 '22 10:12

Jin Yong


2 Answers

First, some reference:

The getElementsByClassName() method of Document interface returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

So, in your particular case, the copyText variable will hold an array of elements (those that have the class hl7MsgBox under the document element). Now, because in your case there is only one element with that class, you can access it using copyText[0] and get all the text wrapped by it with copyText[0].textContent. In summary, you can do something like next to get the text to be copied:

var elems = document.getElementsByClassName("hl7MsgBox");
var copyText = elems[0].textContent;

Another possibility is to use the method querySelector():

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

With the querySelector() method you can simply do:

var copyText = document.querySelector(".hl7MsgBox").textContent;

Finally, we can create a general method called copyToClipBoard() whose only job is to copy the received string to the clipboard an rearrange the code with pure Javascript like this:

const copyToClipBoard = (str) =>
{
    const el = document.createElement('textarea');
    el.value = str;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
};

document.querySelector(".btnCopy").addEventListener("click", function()
{
    var copyText = document.querySelector(".hl7MsgBox").textContent;

    // Or...
    //var elems = document.getElementsByClassName("hl7MsgBox");
    //var copyText = elems[0].textContent;

    copyToClipBoard(copyText);
});
<div class="hl7MsgBox">
    <span class="boxspan">1</span>
    <br>
    <span class="boxspan">2</span>
    <br>
    <span class="boxspan">3</span>
    <br>
    <span class="boxspan">4</span>
    <br>
    <span class="boxspan">5</span>
    <br>
    <span class="boxspan">6</span>
    <br>
    <span class="boxspan">7</span>
    <br>
    <span class="boxspan">8</span>
</div>
<button class="btnCopy">Copy To Clipboard</button>
<br>
<textarea rows=8 cols=50 placeholder="Paste text here..."></textarea>
like image 170
Shidersz Avatar answered Dec 08 '22 00:12

Shidersz


Simply get the text from the DIV and pass it into this function.

function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text); 

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}   

copyToClipboard('hello'); //hello
like image 24
Diego Fortes Avatar answered Dec 08 '22 00:12

Diego Fortes