-2

What is the JavaScript code to select a specific item on a website and copy it to clipboard?

Here is the code, in this case, I would like to select "Happy New Year", the item changes however so I don't really know how to reference it.

<div class="slds-page-header__title slds-m-right--small slds-align-middle fade-text" data-aura-rendered-by="1302:0" title="Happy New Year"><span data-aura-rendered-by="1108:0" class="uiOutputText" data-aura-class="uiOutputText">Happy New Year</span></div>
<span data-aura-rendered-by="1108:0" class="uiOutputText" data-aura-class="uiOutputText">Happy New Year</span>
karel
  • 5,489
  • 46
  • 45
  • 50
  • 1
    Create a – Stefan Avramovic Jan 04 '20 at 15:04
  • 1
    Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – ggorlen Jan 04 '20 at 15:12

1 Answers1

-1

You can try to use document.execCommand('copy').

However, quoting from this MDN

The document.execCommand() method's "cut" and "copy" commands can be used to replace the clipboard's current contents with the selected material. These commands can be used without any special permission if you are using them in a short-lived event handler for a user action (for example, a click handler).

So, one way you can achieve this by getting user's consent to copy to its clipboard by letting it to interact with your DOM.

Code sample (Credit to this answer)

function copy(text) {
  var input = document.createElement('input');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  var result = document.execCommand('copy');
  document.body.removeChild(input);
  return result;
};

function copyText () {
  let text = document.querySelector('.uiOutputText').textContent;
  // alert(copy(text) ? 'Copied' : 'Failed to copy');
  copy(text);
}
<div class="slds-page-header__title slds-m-right--small slds-align-middle fade-text" data-aura-rendered-by="1302:0" title="Happy New Year">
<span data-aura-rendered-by="1108:0" class="uiOutputText" data-aura-class="uiOutputText">Happy New Year</span>
</div>
<br/>
<button type="button" onclick="copyText()"> Copy </button>
choz
  • 17,242
  • 4
  • 53
  • 73