Copy text from an HTML element to clipboard-JavaScript
This article is about how to copy text from an html element to clipboard using JavaScript. You can copy from element with input field.
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
Related Posts
Check if a HTML checkbox is checked using JavaScript
Find out how to check if the checkbox is checked or not using JavaScript.
Disable scrolling Behaviour on a body with element on position fixed in mobile.
In this article we will learn on how to disable the scroll behaviour of a body on a element with position fixed on mobile devices..
How to change the color of <hr> tag using CSS
Here we will learn how to change the color or the background color of HR element in out html using css style.
Horizontal scrolling div with arrows using HTML and CSS
Tutorial on how to make horizontal scrolling div with arrows using html and css and for smooth scrolling we will use scrollBy() function in Javascript.
