简体   繁体   中英

Copy text js to clipboard

I have:

HTML code:

<div class="server-ip clearfix">
<p>
  <i class="ion-ios-world"></i>
  <span id="serv-1">play.minesuperior.com</span>
</p>
<a class="copy-action" href="#!" onclick="copyText('serv-1')">
    <span class="copy-text">
      <i class="ion-scissors"></i>
      Copy
    </span>
</a>
</div>

JS function:

function copyText(textToCopy) {
  var copyText = document.getElementById(textToCopy).textContent;
  console.log(copyText);

  copyText.select();
  document.execCommand("Copy");

  alert("Copied the text: " + copyText);
}

I get error:

Uncaught TypeError: copyText.select is not a function

Why? In function I pass param: play.minesuperior.com . I tryied in console.log put param function and I get my text.

Try below code snippet,

 function CopyToClipboard(containerid) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().addRange(range); document.execCommand("copy"); alert("text copied") ; } 
 <div class="server-ip clearfix"> <p> <i class="ion-ios-world"></i> <span id="serv-1">play.minesuperior.com</span> </p> <a class="copy-action" href="#!" onclick="CopyToClipboard('serv-1')"> <span class="copy-text"> <i class="ion-scissors"></i> Copy </span> </a> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM