Change innerHTML of controller with javascript

Hi. I create a stimulus controller and use on a div element.
Now when change innerHTML of this div element with click on a button, text change but color not change to red and connect() not work.

<div data-controller="test">
    <span>This text color change to red</span>
</div>
<button type="button" data-action="test#changeColor">click</button>

test_controller.js

...
connect() {
    this.element.style.color = "red";
}
changeColor(event) {
    this.element.innerHTML = "<span>HelloWorld!</span>"
}
...

As per connect() not work when change with javascript · Issue #554 · hotwired/stimulus · GitHub - you will need to ensure that the button is inside the controller for it to be a recognised target.

Additional to this, your question on connect() not work when change with javascript · Issue #555 · hotwired/stimulus · GitHub

Hi. I create a stimulus controller and use on a div element.
Now when change innerHTML of this div element with click on a button, text change but color not change to red and connect() not work.

<div data-controller="test">
    <span>This text color change to red</span>
    <button type="button" data-action="test#changeColor">click</button>
</div>

The problem here is that connect does not re-run when you have changeColor called, that is only re-run when the controller connects.

You will need to re-write your controller to something like

connect() {
  this.element.style.color = "red";
 // only runs when initially connected
}
changeColor(event) {
    this.element.style.color = "red";
    this.element.innerHTML = "<span>HelloWorld!</span>"
}
1 Like

@lbee Thank you so much