Dwight Watson's blog

Accessing the root element in Stimulus

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

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 by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.