picostitch
crafting (and) JavaScript
#web

Pseudo-Class :defined Under the Hood

The CSS pseudo-class :defined is for defined (custom) elements, sure. But what does "defined" really mean? While reading about upgrading CBEs I came across the definition for it. Let me quote the DOM spec a bit.

An element’s custom element state is one of "undefined", "failed", "uncustomized", or "custom". An element whose custom element state is "uncustomized" or "custom" is said to be defined.

[...]

Whether or not an element is defined is used to determine the behavior of the :defined pseudo-class.

What is the "custom element state"?

The DOM spec has not much on it. It just says when the value is set to what. There is one example in the spec that shows the four states.

<!DOCTYPE html>
<script>
  window.customElements.define("sw-rey", class extends HTMLElement {})
  window.customElements.define("sw-finn", class extends HTMLElement {}, { extends: "p" })
  window.customElements.define("sw-kylo", class extends HTMLElement {
    constructor() {
      // super() intentionally omitted for this example
    }
  })
</script>

<!-- "undefined" (not defined, not custom) -->
<sw-han></sw-han>
<p is="sw-luke"></p>
<p is="asdf"></p>

<!-- "failed" (not defined, not custom) -->
<sw-kylo></sw-kylo>

<!-- "uncustomized" (defined, not custom) -->
<p></p>
<asdf></asdf>

<!-- "custom" (defined, custom) -->
<sw-rey></sw-rey>
<p is="sw-finn"></p>