Issue retreiving elements with querySelector in Controller

When querying elements in my controller, I am not able to retrieve the elements I want, even though when I run the same code in my browser console it finds them perfectly (the dynamic erb code makes sure the id is title1, for ex). In that sense, I’m wondering if there is some Stimulus information I’m missing as to how to retrieve specific elements when they’re not static or why does Stimulus not like querySelectors.

The code is the following:

a) In app/views/legislations/show.html.erb:

<div data-controller="slideshow">
<% titles.each do |title| %>
   <div id="title<%= title.number %>" data-target="slide">
      <h3>Title <%= title.number %>
   </div>
<% end %>
</div>

b) In app/javascript/controllers/slideshow_controller.js:

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "slide" ];

   showFinished(){
     var firstSection = document.getElementById("title1")
   }
}

Any guidance/help appreciated!

How is the showFinished() method invoked? Is there some part of the controller we can’t see here?

Stimulus has a callback called connect() which is called when the controller is connected to the DOM. It should be possible to query your element from there:

export default class extends Controller {
   connect(){
     var firstSection = document.getElementById("title1")
   }
}

I notice that your slide target is missing the controller name in its descriptor. If you’ve experimented with accessing the target unsuccesfully, that might solve it: data-target="slideshow.slide"

Then you should be able to access the first slide through the targets API:

this.slideTargets[0]