How to copy text from a div to clipboard
Both examples work like a charm :)
JAVASCRIPT:
function CopyToClipboard(containerid) { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select().createTextRange(); document.execCommand("copy"); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().addRange(range); document.execCommand("copy"); alert("Text has been copied, now paste in the text-area") }}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button><br /><br /><div id="div1">Text To Copy </div><br /><textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
how to copy div content into clipboard
I have only been able to copy text from
<input>
and<textarea>
. So my strategy was to copy the text from the<div>
to a invisible<textarea>
.But I couldn't get the copy.value to display in the alert properly (it cancelled the clipboard copy for some reason). So I just used the value of the
copyText
function myFunction() {
// get the div contents
let copyText = document.getElementById("copy").innerHTML;
// get the textarea element
var copy = document.getElementById("copyTextarea");
// move the content from the div to the textarea
copy.value = copyText;
// select the content inside the textarea
copy.select();
copy.setSelectionRange(0, 99999);
// copy to the clipboard
document.execCommand("copy");
// alert
alert("Copied the text: " + copyText);
}You'd need to create your
<div>
and your<textarea>
:<div id="copy" onclick="myFunction()">Simple Test</div>
<textarea style="display: none;" id="copyTextarea"></textarea>Copy text from a div to clipboard using document.execCommand in React
Document.execCommand
will get deprecated in favor of the modern Clipboard API to interact with clipboard.Here is how to use Clipboard API:
function updateClipboard(newClip) {
navigator.clipboard.writeText(newClip).then(
() => {
setCopySuccess("Copied!");
},
() => {
setCopySuccess("Copy failed!");
}
);
}
function copyLink() {
navigator.permissions
.query({ name: "clipboard-write" })
.then((result) => {
if (result.state === "granted" || result.state === "prompt") {
updateClipboard(inputArea.current?.innerText);
}
});
}Notes about using Clipboard API:
The Clipboard API adds greater flexibility, in that you aren't limited to copying the current selection into the clipboard, but can directly specify what information to place into the clipboard.
Using the API requires that you have the permission "clipboardRead" or "clipboardWrite" in your manifest.json file.
The clipboard-write permission is granted automatically to pages when they are in the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard.
Clipboard API (clipboard-write permission) is currently not supported by Firefox but supported by Chrome / Chromium
Or, to use
Document.execCommand
, you should convert thediv
into aninput
ortextarea
(which can be selected) and use CSS to make it look like a div:function copyLink(e) {
inputArea.current?.select();
document.execCommand("copy");
e.target.focus();
setCopySuccess("Copied!");
}
// ...
{shortLink && (
<input
ref={inputArea}
type="text"
className="shorten-text"
value={shortLink}
/>
)}Or, see How to copy text from a div to clipboard if you still want to use
div
.How to copy in clipboard only one DIV from multiple divs using javascript
I was also stuck in same kind of problem. I found the solution.
If you want to show themessage
in the samediv
do this, just tryfunction copyDivToClipboard(id) {
var range = document.createRange();
oldvalue = document.getElementById(id).innerHTML;
range.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
document.getElementById(id).innerHTML = "Text Copied";
setTimeout(function(){document.getElementById(id).innerHTML = oldvalue }, 2000); //you can change the time
}<div id="div1" onclick="copyDivToClipboard(this.id);">Text To Copy div1</div>
<div id="div2" onclick="copyDivToClipboard(this.id);">Text To Copy div2</div>
<div id="div3" onclick="copyDivToClipboard(this.id);">Text To Copy div3</div>
<div id="div4" onclick="copyDivToClipboard(this.id);">Text To Copy div4</div>Copy multiple texts from multiple divs in clipboard
I modified your code a bit please have a look, and see if this helps.
var elements = document.getElementsByClassName("parentDiv");
Array.from(elements).forEach(function(element) {
element.addEventListener('click', copyTextToClipboard);
});
function copyTextToClipboard() {
var selection = window.getSelection();
var range = document.createRange();
let dataToCopy = this.getElementsByClassName('text_to_copy');
range.selectNodeContents(dataToCopy[0]);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
window.getSelection().removeAllRanges()
}<html>
<body>
<div>
<div class="parentDiv">
<span>My favorite actor is <span class="text_to_copy">Robert Downey, Jr.</span></span>
</div>
<div class="parentDiv">
<span>My favorite actor is <span class="text_to_copy">Tom Cruise</span></span>
</div>
<div class="parentDiv">
<span>My favorite actor is <span class="text_to_copy">Hugh Jackman</span></span>
</div>
<div class="parentDiv">
<span>My favorite actor is <span class="text_to_copy">Ryan Gosling</span></span>
</div>
</div>
</body>
</html>Copy text to clipboard from div with javascript
First, some reference:
The
getElementsByClassName()
method of Document interface returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also callgetElementsByClassName()
on any element; it will return only elements which are descendants of the specified root element with the given class names.So, in your particular case, the
copyText
variable will hold an array of elements (those that have the classhl7MsgBox
under the document element). Now, because in your case there is only one element with that class, you can access it usingcopyText[0]
and get all the text wrapped by it withcopyText[0].textContent
. In summary, you can do something like next to get the text to be copied:var elems = document.getElementsByClassName("hl7MsgBox");
var copyText = elems[0].textContent;Another possibility is to use the method querySelector():
The Document method
querySelector()
returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found,null
is returned.With the
querySelector()
method you can simply do:var copyText = document.querySelector(".hl7MsgBox").textContent;
Finally, we can create a general method called
copyToClipBoard()
whose only job is to copy the receivedstring
to the clipboard an rearrange the code with pureJavascript
like this:const copyToClipBoard = (str) =>{ const el = document.createElement('textarea'); el.value = str; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el);};
document.querySelector(".btnCopy").addEventListener("click", function(){ var copyText = document.querySelector(".hl7MsgBox").textContent;
// Or... //var elems = document.getElementsByClassName("hl7MsgBox"); //var copyText = elems[0].textContent;
copyToClipBoard(copyText);});<div class="hl7MsgBox"> <span class="boxspan">1</span> <br> <span class="boxspan">2</span> <br> <span class="boxspan">3</span> <br> <span class="boxspan">4</span> <br> <span class="boxspan">5</span> <br> <span class="boxspan">6</span> <br> <span class="boxspan">7</span> <br> <span class="boxspan">8</span></div><button class="btnCopy">Copy To Clipboard</button><br><textarea rows=8 cols=50 placeholder="Paste text here..."></textarea>
Copying the text inside a div into clipboard upon clicking the div
you can use somthing like this:
HTML:
<button id="btn" onclick="myFunction()">Copy text</button>
JS:
function myFunction() {
var copyText = document.getElementById("btn");
navigator.clipboard.writeText(copyText.textContent)
}Copy more than one div to clipboard and adding characters
The issue is because you're only reading the text from '#divA', as that's the selector passed to the
copyToClipboard()
function.To do what you require amend the logic to create a string in the format you require containing the text of both
#divA
and#divB
:let $divA = $('#divA');
let $divB = $('#divB');
$('button').on('click', e => {
copyToClipboard(`"${$divA.text().trim()}" (${$divB.text().trim()}).`);
});
function copyToClipboard(text) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(text).select();
document.execCommand("copy");
$temp.remove();
}textarea {
width: 300px;
height: 30px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divA">
<p>A certain quote</p>
</div>
<div id="divB">
<p>Author Name</p>
</div>
<button type="button">Copy</button><br /><br />
Paste here to test:<br />
<textarea></textarea>Jquery select() and copy text to clipboard is not working
I've found that
document.execCommand()
is now obselete so I used the Clipboard API$(function () {
$(".copied-toast").hide();
$(".text-copy").click(function () {
var copiedtext = $(this).closest("tr").find(".copy-me").text();
if (navigator.clipboard) {
navigator.clipboard.writeText(copiedtext)
.then(() => {
$(".copied-toast").text("Copied!").show().fadeOut(1200);
})
.catch((error) => {
$(".copied-toast").text("Not copied!").show().fadeOut(1200);
});
} else {
$(".copied-toast").text("Not copied!").show().fadeOut(1200);
}
});
});
Related Topics
Scale a Div to Fit in Window But Preserve Aspect Ratio
How to Disable an Input Type=Text
How to Move All HTML Element Children to Another Parent Using JavaScript
How to Scrape Pages with Dynamic Content Using Node.Js
JavaScript Syntax (0, Fn)(Args)
Angular2:Render a Component Without Its Wrapping Tag
How to Show and Hide Input Fields Based on Radio Button Selection
Jquery Duplicate Div into Another Div
How to Remove Youtube Branding After Embedding Video in Web Page
JavaScript Getcookie Functions
Keyword 'Const' Does Not Make the Value Immutable. What Does It Mean
Keys in JavaScript Objects Can Only Be Strings
Html5 <Audio> Playback with Fade in and Fade Out
Make Checkbox Behave Like Radio Buttons with JavaScript
Class Methods as Event Handlers in JavaScript
Three.Js - Orthographic Camera