0

I have an HTML anchor element and I'd like to copy only the innerText of that element to the clipboard. All the methods I try seem to copy the innerText and the anchor itself, so just pasting what has been copied shows the text as a link. So it seems to be copying the outerHtml for the element. I know I can paste as plain text, but I just want to copy the text. Is there a way to do this that doesn't involve hacky solutions like hidden inputs?

I've tried using both Range.selectNode and Range.selectNodeContents, but both of these seem to behave the same way, and include the anchor in what is copied to the clipboard.

Here's a fiddle illustrating this: https://jsfiddle.net/zjoraen1/

function copyMe {
    getSelection().removeAllRanges();
    var range = document.createRange();
    range.selectNodeContents(document.querySelectorAll("a")[0]);
    getSelection().addRange(range);
    document.execCommand("copy");
}

I expect to paste plain text, but see text formatted as an HTML anchor.

praetorian1
  • 133
  • 1
  • 11

1 Answers1

0

I also can't get it to work even when selecting the text node with document.querySelector('a').childNodes[0], range seems to want to copy as a link.

I would suggest using a function which can copy any text string, your current code won't work on a number of devices anyway e.g. How do I copy to the clipboard in JavaScript?

And just passing the string to that on click - copyToClipboard(document.querySelector('a').innerText)

Dominic
  • 48,717
  • 14
  • 109
  • 126