I'm trying to create a copy button that would copy the text of its previous sibling element to clipboard, without any luck. What am I missing?
Thanks!😊
function copy(elem) {
const word = elem.previousSibling.innerText;
word.select();
wordsetSelectionRange(0, 99999)
document.execCommand('copy');
word.remove();
alert(word + " copied.");
}
words:
<div>
<div>
dog
</div><button
id="it" onclick="copy(this)">copy
</button>
</div>
<div>
<div id="word">
cat
</div><button
id="it" onclick="copy(this)">copy
</button>
</div>
You need the word node, which you can get by just referencing the previousSibling
(don't take its content). Then you can create a range spanning from the beginning of the node to the beginning of the next, then set the window's selection to just that range, and then you can copy the selection:
function copy(elem) {
const wordNode = elem.previousSibling;
const range = document.createRange();
range.setStart(wordNode, 0);
range.setEnd(elem, 0);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
}
words:
<div>
<div>
dog
</div><button id="it" onclick="copy(this)">copy
</button>
</div>
<div>
<div id="word">
cat
</div><button id="it" onclick="copy(this)">copy
</button>
</div>