i'm trying to copy the inner text from a sibling of a pressed button, but i'm not succeeding in finding the element.
It is preferred to use JavaScript but i'll accept JQuery answers as well.
The objective is: press de <a>
and copy to clipboard the inner text of the <span>
.
So far what i managed is ti copy only the inner html of the <a>
, naturally.
This is my HTML, i have several of these on my code (i cannot alter the structure of the html only classes and properties)
<div class="userpas">
<a id="abc" onclick="CopyClipboard(this);" class="copy-dynamic" href="#">copy</a>
<strong style="color: dimgray">Username:</strong>
<span class="a" id="to-copy">password1</span>
</div>
The JS (here)
function CopyClipboard(element) {
var curElementId = element.id;
console.log(curElementId);
// creating new textarea element and giveing it id 't'
let t = document.createElement('textarea')
t.id = 't'
// Optional step to make less noise in the page, if any!
t.style.height = 0
// You have to append it to your page somewhere, I chose <body>
document.body.appendChild(t)
// Copy whatever is in your div to our new textarea
t.value = document.getElementById(curElementId).innerText;
// Now copy whatever inside the textarea to clipboard
let selector = document.querySelector('#t')
selector.select()
document.execCommand('copy')
// Remove the textarea
document.body.removeChild(t)
//MESSAGE
var el = document.createElement('span'),
//copy = document.getElementById('to-copy');
copy = document.getElementById(curElementId);
el.classList.add("message");
el.innerHTML = 'Copied to clipboard';
copy.appendChild(el);
setTimeout(function () {
el.classList.add("show");
setTimeout(function () {
el.classList.remove("show");
}, 3500);
}, 250);
};
EDIT: Context: This is for internal use of the company, so there is no security issues, these are passwords for webdeploys