将前一个兄弟复制到剪贴板

copying previous sibling to clipboard

我正在尝试创建一个复制按钮,用于将其前一个同级元素的文本复制到剪贴板,但没有成功。我错过了什么?
谢谢!

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>

你需要节点这个词,只要引用previousSibling就可以得到(不要取其内容)。然后你可以创建一个从节点开始到下一个节点开始的范围,然后将 window 的选择设置为该范围,然后你可以复制选择:

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>