2

I Want copy inner span text to Clipboard by click on parent element of it, my Html code is like this:

<div> <span> text to copy </span> </div>
<div> <span> text to copy </span> </div>
<div> <span> text to copy </span> </div>

and my Java Script code it is:

const mySpan = document.querySelectorAll('span');

mySpan.forEach(element => {
    var parSpan = element.parentElement;
    parSpan.addEventListener('click', () => {
        var elIn = element.innerHTML;
        document.execCommand('copy');
    });
});

i used of execCommand but its not copied to Clipboard , where is problem?

AmiReza
  • 39
  • 1
  • 7
  • Why should `document.execCommand('copy')` copy the content of `elIn` into the clipboard? How would `document.execCommand('copy')` know to copy the content of `elIn`? – Andreas May 23 '20 at 11:21
  • i dont know, how it can to know this? ;( – AmiReza May 23 '20 at 11:31

2 Answers2

0

Here is some information about copying text from span. You have to create temporary textArea to do so: Copy text from <span> to clipboard

tinokaartovuori
  • 698
  • 4
  • 5
  • 1
    (.execCommand)[https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand] is obsolete, you should use [Clipboard_API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) instead. – ROOT May 23 '20 at 12:21
0

Note: document.execCommand is absolute as mentioned by MDN documentation, You can implement clipboard copy using Clipboard API (write), you can read more about the implementation here, also note that this implementation need user permission to allow browser access to clipboard, this code snippet will not work here since its sandboxed but will work locally:

const mySpan = document.querySelectorAll("span");

mySpan.forEach((element) => {
  var parSpan = element.parentElement;
  parSpan.addEventListener("click", () => {
    navigator.permissions
      .query({
        name: "clipboard-read",
      })
      .then((permissionStatus) => {
        // Will be 'granted', 'denied' or 'prompt':
        console.log(permissionStatus.state);
        if (permissionStatus.state === "granted") {
          navigator.clipboard
            .writeText(element.textContent.trim())
            .then(() => {
              console.log("Text copied to clipboard");
            })
            .catch((err) => {
              // This can happen if the user denies clipboard permissions:
              console.error("Could not copy text: ", err);
            });
          console.log("text copied!!");
        } else {
          console.error("Could not copy text: ", err);
          throw "can't copy, need permission";
        }
        {
          {
            /* cpyText(); */
          }
        }
      });
  });
});
<div> this is parent element!!1 <span> text to copy1 </span> </div>
<div> this is parent element!!2 <span> text to copy2 </span> </div>
<div> this is parent element!!3 <span> text to copy3 </span> </div>
ROOT
  • 11,363
  • 5
  • 30
  • 45