MDN self-hosted library · e01.org

ElementInternals: labels property

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
class CustomCheckbox extends HTMLElement {
  static formAssociated = true;

  constructor() {
    super();
    this.internals_ = this.attachInternals();
    this.internals_.role = "checkbox";
    this.internals_.ariaLabel = "Join newsletter";
  }
}
html
<form id="myForm">
  <custom-checkbox id="custom-checkbox" tabindex="0"></custom-checkbox>
  <label for="custom-checkbox">Join newsletter</label>
</form>
js
class CustomCheckbox extends HTMLElement {
  static formAssociated = true;

  constructor() {
    super();
    this.internals_ = this.attachInternals();
  }

  // …
}

window.customElements.define("custom-checkbox", CustomCheckbox);

const element = document.getElementById("custom-checkbox");
console.log(element.internals_.labels); // NodeList [ label ]