1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WebComponentsに外部(Shadow DOMの外)からイベントリスナーを追加する

Posted at

やりたいこと

WebComponetには手を触れず外からイベントを追加する。

結論

querySelectorとかgetElemetByXxxで要素を特定してshadowRootでアクセスしてよしなにする。

コード

<sample-elem id="hoge"></sample-elem>
class sampleElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({
      mode: 'open'
    });
    this.shadowRoot.innerHTML = `
<style>
p#ev1 { color: red; }
</style>
<p id='ev1'>alert</p>
<p>hoge</p>
`;
    this.ev1 = this.shadowRoot.getElementById('ev1');
  }

  connectedCallback() {
    this.addEventListener('click', this.onClickAll);
    this.ev1.addEventListener('click', this.onClickP);
  }

  disconnectedCallback() {
    this.removeEventListener('click', this.onClickAll)
    this.ev1.removeEventListener('click', this.onClickP);
  }

  onClickAll(e) {
    console.log('onClickAll !');
  }

  onClickP(e) {
    console.log('onClickP !');
  }
}
customElements.define('sample-elem', sampleElement);

// shadow domの外からイベントリスナーを追加
var shadowDom = document.querySelector('sample-elem').shadowRoot;
shadowDom.querySelector("p#ev1").addEventListener('click', () => {alert('#ev1')});

留意点

2020/01/20時点だとElement.shadowRootは実験的な機能です。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?