Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting slot text in Custom Element Shadow DOM

I made a simple copy-paste component with regular html/css/js. I've tried to turn it into a web component and can no longer get the copy-paste behaviour to work.

The markup inside the shadow DOM is basically

<span contenteditable="true">
  <slot></slot>
</span>
<button>Copy</button>

The Javascript:

class CopyPaste extends HTMLElement {
  constructor() {
    super();
    let shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.appendChild(copyPasteTemplate.content.cloneNode(true));
  }

  connectedCallback() {
    let copyButton = this.shadowRoot.querySelector('button');
    let textToCopy = this.shadowRoot.querySelector('span');

    function selectElementContents(el) {
      var range = document.createRange();
      range.selectNodeContents(el);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    }

    function copyText() {
      selectElementContents(textToCopy);
      document.execCommand('copy');
    }

    copyButton.addEventListener('click', copyText);
    textToCopy.addEventListener('click', copyText);
  }
}

window.customElements.define('copy-paste', CopyPaste);
like image 435
Ollie Williams Avatar asked Jan 29 '23 03:01

Ollie Williams


1 Answers

In your example, the textToCopy variable refers to the <slot> element, with no text inside.

If you want to get the ditributed node form the light DOM, of the <copy-paste> element, you should use the assignedNodes() method of the <slot> element:

let textToCopy = this.shadowRoot.querySelector('slot').assignedNodes()[0];

PS: note that the contenteditable attribute may not work as you expect in your given example.

like image 100
Supersharp Avatar answered Jan 30 '23 17:01

Supersharp