Adding a Target

Let's add a DOM element as a target in this lesson.

Targeting DOM elements

In client-side coding, it is fairly common to mark a particular DOM element as elements of interest to the code. Typically this means we are either reading the DOM element’s state to determine what to do or are changing the DOM element’s state as a result of some other event. In our case, it’s the latter. That is, we want to add the DOM class, hidden, to an element to hide it, and eventually we want to change the text of the button itself.

In the frameworkless world, or in the jQuery world, we would identify these elements using a DOM ID or DOM class. Because those DOM attributes are also used to manage CSS styling, however, what DOM ID or class elements are styling and which are used by JavaScript can be confusing.

Stimulus allows us to identify DOM elements of interest by marking them as targets. A target is identified using a specially named attribute of the format data--target attribute on a DOM element. The value of the attribute is the name of the target. Target names need to be in camelCase in the HTML attribute.

Note: Stimulus 1.0 used a different syntax here: data-target=<controller name>.targetName. Older code may display that structure.

Our target element is the element we want to hide. In this case, that’s the body of the list, which is currently not its own div element. Let’s make it so:

Get hands-on with 1000+ tech skills courses.