简体   繁体   中英

Issue retreiving dynamic elements with querySelectors in Stimulus 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 (I can see the id is title1 in my Inspector, 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!

Could you provide some context around when the showFinished action in the slideshow controller is called? I don't think Stimulus has anything against querySelectors because they appear to make use of them under the hood!


I'm not certain this has anything to do with the issue that you're experiencing, but I want to point out something related to the naming convention used in Stimulus in case it is causing other weird side-effects. In the documentation for Targets , they show that the naming convention for a data-target is controller-identifier.target-name :

<div data-controller="search">
  <input type="text" data-target="search.query">
  <div data-target="search.errorMessage"></div>
  <div data-target="search.results"></div>
</div>

In this example, search is the controller-identifier and query , errorMessage , and results are 3 different target-name s. To use this convention, you should have something like this:

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

Note: I also added a missing </h3> tag which I also don't think has anything to do with the issue you're experiencing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM