The other day I wrote a whole thing about web components, but mostly it was about deciphering this, constructors, and classes in JavaScript.

Truth is, I’ve worked with web components for years but I haven’t written very many library-free ones (I’ve used Lit and Stencil a good bit). As luck would have it, I had a good excuse to make one at work today. Figured it was worth sharing.

So, the situation was we had a group of many checkboxes, and we wanted to add an additional “Select all” checkbox that would check or uncheck all of them at once.

Pretty typical markup:

<fieldset>
  <legend>Why didn’t you write about web components sooner?</legend>

  <div>
    <!-- this is our "special" controlling checkbox -->
    <label>
      <input type="checkbox" id="select-all" />
      Select all
    </label>
  </div>

  <label>
    <input type="checkbox" name="excuses" value="hungry" />
    Thought about it; got hungry
  </label>
  <label>
    <input type="checkbox" name="excuses" value="distracted" />
    Distracted by other shiny thing
  </label>
  <label>
    <input type="checkbox" name="excuses" value="imposter-syndrome" />
    What do I know I'm just some guy
  </label>
</fieldset>

The existing script for the app did the old-fashioned script thing where it’d wait for the document to finish, then set up all the event listeners…

document.addEventListener('DOMContentLoaded', () => {
  const selectAll = document.getElementById('select-all')
  const checkboxes = document.querySelectorAll('[name="excuses"]')

  selectAll.addEventListener('change', (event) => {
    // and so on…
  })

  // and so on with other initialization and event listeners
})

But this seemed like the sort of thing where a so-called HTML web component that enhances an existing element might be a better way to organize the logic. Plus, it’d be reusable!

So, with a hat-tip to Zach Leatherman for the name, I give you <select-allosaurus />!

[Pauses for applause for the punny name. No applause is forthcoming.]

OK, then!

Wrap your special “select all” checkbox with it, specifying a CSS selector for the other checkboxes on the target attribute:

<select-allosaurus target="[name='excuses']">
  <label>
    <input type="checkbox" id="select-all" />
    Select all
  </label>
</select-allosaurus>

If you’d prefer to skip my whole journey and jump to the final code, that’s down here, along with a CodePen of it my final component in action.

First pass

So here was my first pass at that component:

class SelectAllosaurus extends HTMLElement {
  connectedCallback() {
    const selectAllCheckbox = (this.selectAllCheckbox =
      this.querySelector('input[type="checkbox"]'))

    if (!selectAllCheckbox) return

    selectAllCheckbox.addEventListener('change', this.selectAllChangedCallback)
  }

  getOtherCheckboxes() {
    const selector = this.getAttribute('target')
    return [...document.querySelectorAll(selector)]
  }

  selectAllChangedCallback(event) {
    const newChecked = event.target.checked
    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.checked = newChecked
    })
  }
}

customElements.define('select-allosaurus', SelectAllosaurus)

So the connectedCallback() method looks for a child element checkbox, then adds an event listener that fires the selectAllChangedCallback() method when that checkbox’s value changes.

When that happens, we look up all the other checkboxes using the target attribute in the markup as a selector. Then we set all their checked attributes to match the “Select all” checkbox.

I felt pretty good about this chunk of code, tried it out, and of course it… didn’t work!

Can you spot the bug?

Fixing issues with “this” in class methods

This is one of those things where I’ve footgun’d myself a billion times while writing older-style React components with their class syntax.

The problems starts when I added that event listener like so…

selectAllCheckbox.addEventListener('change', this.selectAllChangedCallback)

This is an extremely common mistake when dealing with this and callbacks in class code. What this is roughly equivalent to is writing:

const selectAllChangedCallback = this.selectAllChangedCallback
selectAllCheckbox.addEventListener('change', selectAllChangedCallback)

… and you might recall from very early in my last article that strange things happen with the value of this in a method when you separate a method from its parent object and call it later.

In our case, with the method effectively stripped from its context, this will no longer be our custom element. It’ll weirdly be undefined now?! So that results in an error when we try to call the selectAllChangedCallback off of undefined.

This is very avoidable! We have a few options.

Option One is to use an arrow function for the callback to addEventListener:

selectAllCheckbox.addEventListener('change', (event) => {
  this.selectAllChangedCallback(event)
})

One of the most charming aspects of arrow functions — besides their terse syntax — is that they maintain the current contextual value of this as they’re passed around. Handy!

So now selectAllChangedCallback is re-attached to this (our custom element) and this won’t change later. Problem solved.

Option Two is to use the function method .bind, which lets you specify what this will be any subsequent times a function is called:

const callback = this.selectAllChangedCallback.bind(this)
selectAllCheckbox.addEventListener('change', callback)

I mean, this.whateverMethod.bind(this) feels so unnecessary, but it works.

But! You have to remember (and also know precisely when) you have to tack .bind(this) on a method. And a lot of people don’t know precisely when they have to do this, because, and I cannot stress this enough, basically no one writing JavaScript understands how this works, except me and you if you read my last article (and hoo boy did I gloss over a lot of nuance there).

Anyway, another drawback to this is if you have method calls sprinkled elsewhere in other methods, you might have to .bind(this) all of those as well, which is easy to forget.

To avoid that problem, Option Three is basically Nuclear Option Two. Here you reflexively use .bind(this) for every class method in the constructor():

class extends HTMLElement {
  constructor() {
    super()

    this.someMethod = this.someMethod.bind(this)
    this.someOtherMethod = this.someOtherMethod.bind(this)
  }

  someMethod() {}

  someOtherMethod() {}
}

Now when we make an instance of the class, we’re overriding all the methods with functions that are now perma-this’d to our new object.

That’s pretty safe! I see folks using this pattern a lot in the wild. But it also sucks because when you add or remove or rename class methods you also have to add or remove or rename those bound redefinitions in the constructor. Tedious!

Ah, but clever people put all our options together and figured out that defining a class property like so:

class extends HTMLElement {
  something = 42
}

… is syntax sugar for setting a property to that value in the constructor, like this…

class extends HTMLElement {
  constructor() {
    super()
    this.something = 42
  }
}

… so if you were to define a property with an arrow function…

class extends HTMLElement {
  someMethod = () => {
    // do stuff with "this"
  }
}

…that’s basically the same thing as…

class extends HTMLElement {
  constructor() {
    super()

    this.someMethod = () => {
      // do stuff with "this"
    }
  }
}

Because arrow functions inherit this from the context in which they’re defined, that’s not terribly different from using .bind(this) on a method of the same name…

class extends HTMLElement {
  constructor() {
    super()

    this.someMethod = this.someMethod.bind(this)
  }

  someMethod() {
    // do stuff with "this"
  }
}

…which looks just like Option Three, but you only had to write…

class extends HTMLElement {
  someMethod = () => {
    // do stuff with "this"
  }
}

… and not dink around manually with .bind(this) in the constructor. Huzzah!

Because life’s too short for dealing with this problems, I define custom class methods with arrow functions defensively by default.

So, let’s fix my class:

class SelectAllosaurus extends HTMLElement {
  connectedCallback() {
    // SNIP same as before
  }

  // arrow functions for defining methods now
  getOtherCheckboxes = () => {
    const selector = this.getAttribute('target')
    return [...document.querySelectorAll(selector)]
  }

  selectAllChangedCallback = (event) => {
    const newChecked = event.target.checked
    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.checked = newChecked
    })
  }
}

That works!

Here’s a CodePen with everything up to this point in action.

Update: After publishing this I learned from Jared White about the built-in handleEvent() method (via Andrea Giammarchi), which offers some intriguing possibilities here too. You could just watch for a change event on the component itself with this.addEventListener('change', this), then you can catch the bubbling-up change events from a child checkbox in the handleEvent() method. As a bonus, you avoid this entire goddamn problem where your event handler callbacks need to be bound to this somehow. Loving all the blog chatter about web components lately!

Handling indeterminate states

Now, if you play around with that, you might notice that if you select all of the checkboxes, then clear some of them, the “Select all” box stays checked.

Screen capture of a bunch of checkboxes.

Ideally our special checkbox would reflect this things-are-neither-all-checked-nor-all-unchecked state with indeterminate.

That’s just a few more event listeners, so let’s add that:

class SelectAllosaurus extends HTMLElement {
  connectedCallback() {
    const selectAllCheckbox = (this.selectAllCheckbox =
      this.querySelector('input[type="checkbox"]'))

    if (!selectAllCheckbox) return

    selectAllCheckbox.addEventListener('change', this.selectAllChangedCallback)

    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.addEventListener('change', this.update)
    })

    // initial checked/indeterminate setting
    this.update()
  }

  getOtherCheckboxes = () => {
    const selector = this.getAttribute('target')
    return [...document.querySelectorAll(selector)]
  }

  selectAllChangedCallback = (event) => {
    const newChecked = event.target.checked
    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.checked = newChecked
    })
  }

  update = () => {
    const otherCheckboxes = this.getOtherCheckboxes()
    const allChecked = otherCheckboxes.every(({ checked }) => checked)
    const allNotChecked = otherCheckboxes.every(({ checked }) => !checked)

    this.selectAllCheckbox.checked = allChecked
    this.selectAllCheckbox.indeterminate = !(allChecked || allNotChecked)
  }
}

Here’s a Codepen with that additional indeterminate handling added.

Mounting problems

So in my previous article, I urged folks to try to do as much setup work as possible in the connectedCallback method, because that’s what runs when an element is actually added to the page.

Turns out there’s some nuance to that.

Of course there is.

So that all works perfectly well, assuming our custom <select-allosaurus /> element gets defined after the page is mostly finished loading.

Like, roughly your page markup is

<select-allosaurus target="[name='excuses']">
  <!-- snip -->
</select-allosaurus>

<!-- the rest of your page -->

<!-- or loading an external script, or using defer… -->
<script>
  class SelectAllosaurus extends HTMLElement {
    // snip
  }
  customElements.define('select-allosaurus', SelectAllosaurus)
</script>

This way, the page’s DOM has been parsed already and we’re just waiting for our currently-doing-nothing element to be “upgraded” when customElements.define runs. Then its connectedCallback will run, we’ll be able to query for any child elements, and everything is good.

BUT, what if you were to define your component before it’s in the page?

<script>
  class SelectAllosaurus extends HTMLElement {
    // snip
  }
  customElements.define('select-allosaurus', SelectAllosaurus)
</script>

<!-- the rest of your page -->

<select-allosaurus target="[name='excuses']">
  <!-- snip -->
  <input type="checkbox" />
</select-allosaurus>

I thought this would be fine, but it’s really not. In my connectedCallback, I’d query for a child input and this.querySelector wouldn’t find it.

But, uh, it’s there! Right??

Wrong! Ish. When a custom element has been defined already and then it’s added to the page, the DOM parser is basically super greedy about initializing that element. It’s all

  1. Ah, I see a <select-allosaurus> and I know what that is! Let me run its constructor()!
  2. Oh, it has attributes! Maybe I’ll run the attributeChangedCallback()!
  3. OK great now I’ll run connectedCallback()!
  4. Cool cool cool let’s keep working our way down the document and oh butterbeans <select-allosaurus> has some child elements! I’ll deal with those now…

Put another way, connectedCallback() happens when the parser sees an opening tag, not after it has gone through any children and found the closing tag.

So if you’re querying for child elements in connectedCallback, that might not always, uh, work, because the browser at that point doesn’t even know those child elements exist in the tree.

This is a bummer, because I thought one of the most promising parts of using web components to enhance child elements in this fashion was that you could just stop caring about when and how to initialize them.

My in-brain model was the browser would see the element and its children, then handle initialization for you (via connectedCallback, ideally), so you’d always be good to go. Turns out, this is not entirely correct.

So what we really need is a callback that happens after all of an elements children have been parsed. That should be the best time to initialize all our stuff in our wrapper component. … Right?

Whelp, turns out that’s so complicated that the Web Incubator Community Group has been going back and forth around it for over 4 years now. Which doesn’t help us right now.

So what can we do about it right now?

Like with avoiding method + this shenanigans, we’ve got a few options.

Option One is bringing in Andrea Giammarchi’s HTMLParsedElement class and extending off of that, which now provides a parsedCallback() method:

import HTMLParsedElement from 'https://unpkg.com/html-parsed-element/esm/index.js'

class extends HTMLParsedElement {
  parsedCallback() {
    // children will be parsed at this point
  }
}

Option Two, which is robust but also uggggggh, would be to set up a MutationObserver in your constructor, watching for any children to get added or removed from the custom element:

class extends HTMLElement {
  constructor() {
    super()

    this.mutationObserver = new MutationObserver(records => {
      for (const {addedNodes, removedNodes} of records) {
        for (const addedNode of Array.from(addedNodes)) {
          // do some checks, maybe run this.setup if things look good
        }
        for (const removedNode of Array.from(removedNodes)) {
          // do some checks, maybe clean things up?
        }
      }
    })

    // start watching for added/removed child nodes
    this.mutationObserver.observe(this, {childList: true, subtree: true})
  }

  setup = () => {
    // do your setup code
  }
}

Option Three is Fuck This Don’t Overthink It Just Use setTimeout():

class extends HTMLElement {
  connectedCallback() {
    setTimeout(() => {
      // do your setup code
      // children will be parsed now

      // note the arrow function so "this" still works!
    })
  }
}

And that works! It’s fine!

But setTimeout always feels like the last resort of scoundrels, even though this is perfectly functional.

Finally, I saw an intriguing option in this great article on web components by Thomas Wilburn, who knows a thing or thousand about them. He points out that you could use the shadow DOM…

[Boos, hisses from the audience]

Whoa whoa whoa whoa whoa I know that it feels like we’re all trying to avoid that, but hear me out! We set up possibly the simplest shadow DOM possible, a single <slot>, in the constructor:

class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({mode: 'open'})
    this.shadowRoot.innerHTML = '<slot></slot>'
  }
}

With one default <slot>, any child element will get teleported into our element’s shadow DOM.

The great part of slotted content is that it’s still very much “part” of the parent document. Unlike elements and styles solely defined in the shadow DOM of a component, slotted elements still get CSS from the parent page and appear as direct children of the element without having to jump through hoops like querying element.shadowRoot.

Also! When slots get filled, there’s a slotchange event! Here’s what Thomas says about that:

slotchange is basically connectedCallback, but for direct children instead the custom element itself: you get notified whenever the elements in a slot are added or removed.

Which is, basically, exactly what we want! Let’s set that up:

class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({mode: 'open'})
    this.shadowRoot.innerHTML = '<slot></slot>'

    this.shadowRoot.addEventListener('slotchange', this.setup)
  }

  setup = () => {
    // do all the setup code, event listeners, etc
    // can query for child elements with this.querySelector etc
  }
}

Now your setup code will work, regardless of whether the element is defined super early, upgraded later, dynamically inserted in the DOM, whatever.

Hiding everything until setup

If our script around this component fails to load or execute for whatever reason, we’re in a pickle: we’ll have our child checkbox visible, but it does nothing at all. Not ideal!

This could be a real solid use case for having the component just create its own checkbox via script — discarding the whole “I’ll just enhance an existing input” thing.

However, I decided against that because this component will have to support a whole bunch of design systems and frameworks that all have different ideas of what the markup for a checkbox looks like (which is a separate problem but so it goes). We’ve got more custom web components, we’ve got input + label side-by-side, we’ve got labels wrapping inputs, we’ve got visually hidden inputs controlling SVG “checkboxes”, you name it.

So this is just more useful for folks if this is a “BYO checkbox” situation.

But how can we hide this until it sets up?

I mean, there’s like a hundred ways, but a simple one is to add the hidden attribute to the element:

<select-allosaurus hidden target="input[name='excuses']">
  <!-- add input[type=checkbox] somewhere -->
</select-allosaurus>

Then remove that attribute in its script:

setup = () => {
  // SNIP other bits

  this.hidden = false
}

Done! Ish! Worth noting that the hidden attribute does hide elements but it’s pretty “weak”; my global stylesheets typically have something like

[hidden] {
  display: none !important;
}

to beef it up.

The final component code

Here’s putting all that together with the component definition:

class SelectAllosaurus extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.innerHTML = '<slot></slot>'
    this.shadowRoot.addEventListener('slotchange', this.setup)
  }

  setup = () => {
    const selectAllCheckbox = (this.selectAllCheckbox =
      this.querySelector('input[type="checkbox"]'))

    if (!selectAllCheckbox) return

    this.hidden = false

    selectAllCheckbox.addEventListener('change', this.selectAllChangedCallback)

    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.addEventListener('change', this.update)
    })

    // initial checked/indeterminate setting
    this.update()
  }

  getOtherCheckboxes = () => {
    const selector = this.getAttribute('target')
    return [...document.querySelectorAll(selector)]
  }

  selectAllChangedCallback = (event) => {
    const newChecked = event.target.checked
    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.checked = newChecked
    })
  }

  update = () => {
    const otherCheckboxes = this.getOtherCheckboxes()
    const allChecked = otherCheckboxes.every(({ checked }) => checked)
    const allNotChecked = otherCheckboxes.every(({ checked }) => !checked)

    this.selectAllCheckbox.checked = allChecked
    this.selectAllCheckbox.indeterminate = !(allChecked || allNotChecked)
  }
}

Register it at any time, even before parsing the entire DOM like so:

customElements.define('select-allosaurus', SelectAllosaurus)

And wrap it around your desired checkbox (you provide whatever input and label you like!) like so:

<select-allosaurus hidden target="input[name='excuses']">
  <label>
    <input type="checkbox" />
    Select all
  </label>
</select-allosaurus>

Neat!

Here’s a CodePen with this complete, sorta-Shadow-DOM-y version in action. Note that I define the component in the HTML section now, before it appears in the markup and it still works.

This could be even more robust by implementing the child checkbox change event via the handleEvent() method — which would probably let us avoid using the shadow DOM entirely — and also I really should be adding (and removing!) event listeners on the “other” checkboxes via attributeChangedCallback() in case someone adjusts the target after the fact, but this is Good Enough For Now™ and also this article is too long already.

OK fine let’s make it better

(Added 19 December 2023) This was gnawing on me, so here’s a version of the component with all those changes:

class SelectAllosaurus extends HTMLElement {
  static observedAttributes = ['target']

  constructor() {
    super()

    // basic shadow DOM with a slot
    // lets us run a callback if/when the children change via `slotchange`
    this.attachShadow({ mode: 'open' })
    this.shadowRoot.innerHTML = `
      <style>
        :host { display: block; }
        :host[hidden] { display: none; }
      </style>
      <slot></slot>`
    this.shadowRoot.addEventListener('slotchange', this.onSlotChange)
  }

  // the only observed attribute is "target"
  // but if it changes, we need to figure out the new status of our checkbox
  attributeChangedCallback(name, oldValue, newValue) {
    this.update()
  }

  connectedCallback() {
    // this funnels through this.handleEvent
    this.addEventListener('change', this)

    document.addEventListener('change', this.onDelegatedChange)
  }

  // cleanup
  disconnectedCallback() {
    this.removeEventListener('change', this)
    document.removeEventListener('change', this.onDelegatedChange)
  }

  getSelectAllCheckbox = () => {
    return this.querySelector('input[type="checkbox"]')
  }

  getOtherCheckboxes = () => {
    const selector = this.getAttribute('target')
    return [...document.querySelectorAll(selector)]
  }

  // this is the "change" event callback
  handleEvent(event) {
    const newChecked = event.target.checked
    this.getOtherCheckboxes().forEach((checkbox) => {
      checkbox.checked = newChecked
    })
  }

  onSlotChange = () => {
    const selectAllCheckbox = this.getSelectAllCheckbox()
    if (!selectAllCheckbox) return

    this.hidden = false

    // initial checked/indeterminate setting
    this.update()
  }

  onDelegatedChange = (event) => {
    const targets = this.getOtherCheckboxes()
    if (targets.includes(event.target)) {
      this.update()
    }
  }

  update = () => {
    const selectAllCheckbox = this.getSelectAllCheckbox()

    if (!selectAllCheckbox || !this.isConnected) return

    const otherCheckboxes = this.getOtherCheckboxes()

    const allChecked = otherCheckboxes.every(({ checked }) => checked)
    const allNotChecked = otherCheckboxes.every(({ checked }) => !checked)

    selectAllCheckbox.checked = allChecked
    selectAllCheckbox.indeterminate = !(allChecked || allNotChecked)
  }
}

I’ve shifted some things around and renamed some methods, but the big changes are:

  • I’m putting a change event listener on the component itself (instead of the wrapped checkbox) with this.addEventListener('change', this). Now, we don’t have to worry about adding or removing an event listener on any children checkboxes should those change after the fact; the one handleEvent callback will take care of any checkbox change, regardless of the child checkbox that triggered it.
  • I thought the above would let me get rid of the shadow DOM entirely, but the slotchange is still useful for managing the hidden attribute and running an update() if the child nodes change at some point.
  • Also, because I still have a shadow DOM anyway, I include some rudimentary scoped styles (mostly for handling hidden) so implementers don’t have to.
  • Instead of sticking an event listener on all the target checkboxes, I’m using event delegation with a single change event listener on the document. With event delegation, I don’t have to concern myself with adding or removing listeners on the other checkboxes directly and I don’t have to worry about what happens if the target attribute changes; I just have to manage the single callback on the document and the the update() method will figure out the right thing to do when a change happens.
  • I’ve set up the target attribute as one of the observedAttributes, so if you were to change that at some point, the component will set things straight via update().

That’s a little more robust! Here’s a CodePen with this latest version in action.