DOM

Element.part プロパティ

 編集:2022.09.20 by T.A.

[Edge]。→

element の部品識別子(すなわち part 属性を使用して設定されたもの)を DOMTokenList で返します。

これらはシャドウ DOM の部品を ::part 擬似要素でスタイル付けするために使用することができます。

構文
element.part
element Element オブジェクト。

DOMTokenList オブジェクト。

mdnのサンプル:

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Shadow parts example</title>
  <script src="main.js" defer></script>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Shadow part styling for tabbed custom element</h1>

  <template id="tabbed-custom-element">
    <style type="text/css">
      *, ::before, ::after {
        box-sizing: border-box;
        padding: 1rem;
      }
      :host {
        display: flex;
      }
    </style>
    <div part="tab active">Tab 1</div>
    <div part="tab">Tab 2</div>
    <div part="tab">Tab 3</div>
  </template>

  <tabbed-custom-element></tabbed-custom-element>

</body>
</html>

style.css:

tabbed-custom-element::part(tab) {
  color: #0c0c0dcc;
  border-bottom: transparent solid 2px;
}

tabbed-custom-element::part(tab):hover {
  background-color: #0c0c0d19;
  border-color: #0c0c0d33;
}

tabbed-custom-element::part(tab):hover:active {
  background-color: #0c0c0d33;
}

tabbed-custom-element::part(tab):focus {
  box-shadow:
    0 0 0 1px #0a84ff inset,
    0 0 0 1px #0a84ff,
    0 0 0 4px rgba(10, 132, 255, 0.3);
}

tabbed-custom-element::part(active) {
  color: #0060df;
  border-color: #0a84ff !important;
}

main.js:

let template = document.getElementById("tabbed-custom-element");

globalThis.customElements.define(template.id, class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content);

    let tabs = [];
    let children = this.shadowRoot.children;

    for(let elem of children) {
      if(elem.getAttribute('part')) {
        tabs.push(elem);
      }
    }

    tabs.forEach((tab) => {
      tab.addEventListener('click', (e) => {
        tabs.forEach((tab) => {
          tab.part = 'tab';
        })
        e.target.part = 'tab active';
      })

      console.log(tab.part);
    })
  }
});

テスト