Copy text from an HTML element to clipboard-JavaScript

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more