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 call getElementsByClassName()
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 class hl7MsgBox
under the document element). Now, because in your case there is only one element with that class, you can access it using copyText[0]
and get all the text wrapped by it with copyText[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 received string
to the clipboard an rearrange the code with pure Javascript
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>