Adding a Target
Let's add a DOM element as a target in this lesson.
We'll cover the following
Targetting DOM elements
In client-side coding, it is fairly common to have to mark a particular DOM element as being of interest to the code. Typically this means either you are reading the DOM element’s state to determine what to do or you are changing the DOM element’s state as a result of some other event. In our case, it’s the latter: we want to add the DOM class is-hidden
to an element to hide it, and eventually we want to change the text of the button itself.
In the framework-less world, or in jQuery world, we would typically identify these elements using a DOM ID or DOM class. However, since those DOM attributes are also used to manage CSS styling, it can be confusing as to what DOM ID or class elements are styling and which are used by JavaScript.
Stimulus allows you to explicitly identify DOM elements of interest by marking them as targets. A target is identified using a specially named attribute of the format data-<controller name>-target
on a DOM element. The value of the attribute is the name of the target.
Note: Stimulus 1.0 used a different syntax here:
data-target=<controller name>.targetName
. You may see older code with that structure.
Our target element is the element we want to hide. It’s currently identified as having the DOM class js--day-text
from our framework-less toggle, but let’s also make it a target:
<section class="js--day-text" data-day-toggle-target="thingToHide">
That sets up the target on the HTML side, but we also need to declare the target within the controller, and the mechanism is a little different depending on whether you are using TypeScript or JavaScript. Here’s the way it works in TypeScript:
Get hands-on with 1200+ tech skills courses.