Nuno cruz Nuno cruz - 1 year ago 181
HTML Question

Copy text inside sibling of button without plugins

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

and copy to clipboard the inner text of the

So far what i managed is ti copy only the inner html of the
, 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>

The JS (here)

function CopyClipboard(element) {

var curElementId =;


// creating new textarea element and giveing it id 't'
let t = document.createElement('textarea') = 't'

// Optional step to make less noise in the page, if any! = 0

// You have to append it to your page somewhere, I chose <body>

// 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')

// Remove the textarea

var el = document.createElement('span'),
//copy = document.getElementById('to-copy');
copy = document.getElementById(curElementId);

el.innerHTML = 'Copied to clipboard';


setTimeout(function () {


setTimeout(function () {


}, 3500);

}, 250);


This is for internal use of the company, so there is no security issues, these are passwords for webdeploys

Answer Source

you can try something like that for getting the span inner html

   var spanElement = element.nextSibling;

   while (!spanElement.tagName || spanElement.tagName !== 'SPAN') {
       spanElement = spanElement.nextSibling

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download