Stimulus Discourse

Data-target doesnt work at all


#1

Hey guys,

When i try to use target, i get this error:

TypeError: undefined is not an object (evaluating 'this.homeTarget.innerHTML'

this.homeTarget is undefined

HTML:

<div class="home" id="home" data-controller="main" data-action="click->main#start_quiz" data-target="main.home">
	<div class="home__wrapper">
		<div class="home__heading">BEM VINDO AO QUIZ</div>
		<div class="home__subheading">TOQUE NA TELA PARA INICIAR</div>
	</div>
</div>

Javascript:

import { Controller } from "stimulus"
export default class extends Controller {
	static targets = [ "home" ]
        start_quiz() {
		console.log("home:", this.homeTarget.innerHTML)
	}
}

What’s wrong here?


#2

Have you tried not chaining it?

const home = this.homeTarget;
let homeHTML = home.innerHTML;

#3

This was resolved in https://github.com/stimulusjs/stimulus/issues/156#issuecomment-388790560


#4

Total side note to your actual issue: If a node is the root element of a controller, you shouldn’t need to make it a target of the same controller. Just use this.element.

HTML:

<div class="home" id="home" data-controller="main" data-action="click->main#start_quiz"">
	<div class="home__wrapper">
		<div class="home__heading">BEM VINDO AO QUIZ</div>
		<div class="home__subheading">TOQUE NA TELA PARA INICIAR</div>
	</div>
</div>

Javascript:

import { Controller } from "stimulus"
export default class extends Controller {
    start_quiz() {
        console.log("home:", this.element.innerHTML)
    }
}