TIL you can easily access a Stimulus JS controller's root element

Oliver Peate posted on May 7th, 2020

In the past I’ve added a wrapper target to the enclosing HTML element to allow access in the Stimulus JS controller:

<div data-controller="subscription" data-target="subscription.wrapper"></div>

However, you can forego this extra target and use this.element instead to access the root element within the controller. This is particularly useful when you want to read data attributes for configuration, for example:

<div data-controller="subscription" data-stripe-key="<%= ENV.fetch('STRIPE_KEY') %>"></div>
export default class extends Stimulus.Controller {
  initialize() {
    const publicKey = this.element.dataset.stripeKey;
    this.stripeClient = Stripe(publicKey);
  }
}

Reference: Stimulus controller properties

What did you learn today?

Write a quick TIL post to reflect on what you've learned.

Write a post