Neon Tsunami

Accessing the root element in Stimulus

January 09, 2018

Sometimes you might want to access the root element of your controller when using Stimulus - the element you have the data-controller attribute attached to. You could hook up a target to get access to it, but there’s an easier way - it’s simply available on your controller as this.element.

export default class extends Stimulus.Controller {
  connect() {
    // toggle class on the root element
    this.element.classList.toggle('element--connected')
  }
}

A blog about Laravel & Rails, written by Dwight Watson.