Copy text from an HTML element to clipboard-JavaScript


📋 Table Of Content

In this article we will learn, how to copy text from an HTML element to clipboard using JavaScript.

Copying text from a website usually required us to select the whole paragraph or a line and then right-click and then copy the text. While its very easy to do that in desktop, but with mobile its really not that easy if its a long paragraph.

So, in this article we will copy text from HTML DOM element with click of a button using vanilla JavaScript.

Here we copy text to clipboard JavaScript without input field. Using this you can copy fromany div or p tag or span tag too.

Let see how to do it .

Copy Text to Clipboard

Here we will use navigator.clipboard that helps to implement cut, copy and paste with web application.

HTML code:

<body>
    <div id="text">Hello how are you?</div>
    <button class="copy-text" id="btn" onclick="copyText()">Copy Text</button>
    <script src="script.js"></script>
 </body>

JavaScript Code:

function copyText(){
  const text = document.getElementById('text').innerText
  const btnText = document.getElementById('btn')
  navigator.clipboard.writeText(text);
  btnText.innerText = "Copied Text"
}

Code Explanation

Here, we have a div with some text and an id (text) and a button with a onclick() function.

When we click the button, it will run the copyText() function.

Inside the copyText() function, we have got the text inside the div using document.getElementById('text').innerText and then we got the button using the id.

So when the function is triggered, we write the text to the clipboard using navigator.clipboard.writeText(text) and then change the inner text of the button to "Copied Text".

Related Topics:

Enable or Disable button programmatically using JavaScript

Change Background Color Using JavaScript

Change Text Color Using JavaScript With Example

Check If A HTML Checkbox Is Checked Using JavaScript


💾 Recommended Articles