Missing Target Element

I’ve read the other posts with this error, but the solutions, as far as I understood them don’t seem to work for me.

The error in Chrome’s console:
Uncaught Error: Missing target element "channel.messages"

My view:

<div class="col-sm-10" data-controller="channel" data-channel-id="<%= @channel.id %>">
  <!-- Chat messages -->
  <div class="pr-6 py-4 flex-1">
    <div data-target="channel.messages">
      <%= render @channel.messages %>
    </div>
        <div class="pb-6 pr-4 flex-none">
          <div class="flex rounded-lg border-2 border-grey overflow-hidden">
            <span class="text-3xl text-grey border-r-2 border-grey p-2">
              <svg class="fill-current h-6 w-6 block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M16 10c0 .553-.048 1-.601 1H11v4.399c0 .552-.447.601-1 .601-.553 0-1-.049-1-.601V11H4.601C4.049 11 4 10.553 4 10c0-.553.049-1 .601-1H9V4.601C9 4.048 9.447 4 10 4c.553 0 1 .048 1 .601V9h4.399c.553 0 .601.447.601 1z"/></svg>
            </span>
            <input type="text" class="w-full px-4" placeholder="Message <%= @other_user.name %>" />
          </div>
      </div>
    </div>
  </div>

  <%= form_with model: [@channel, Message.new], data: { action: "ajax:success->channel#clearMessage" } do |form| %>
    <%= form.text_field :body, class: "form-control", data: { target: "channel.newMessage" } %>
  <% end %>
</div>

_messages partial:

<div>
  <div class="font-weight-bold"><%= message.user.name %></div>
  <div><%= message.body %></div>
</div>

my controller:

import { Controller } from "stimulus"
import consumer from "channels/consumer"

export default class extends Controller {
  static targets = [ "messages", "newMessage" ]

  connect() {
    this.subscription = consumer.subscriptions.create({ channel: "MessageChannel", id: this.data.get("id") }, {
      connected: this._connected.bind(this),
      disconnected: this._disconnected.bind(this),
      received: this._received.bind(this)
    })
  }

  disconnect() {
    consumer.subscriptions.remove(this.subscription)
  }

  _connected() {
  }

  _disconnected() {
  }

  _received(data) {
    if (data.message) {
      this.messagesTarget.insertAdjacentHTML('beforeend', data.message)
    }
  }

  clearMessage(event) {
    this.newMessageTarget.value = ''
  }
}

When I inspect the HTML, it shows:
<div data-target="channel.messages">

Where is data-controller defined in the HTML?

Sorry, I cut it off when pasting in the code. I updated the code in my post to show the controller.

Thank you!

Can you provide a complete example of all HTML generated on a page, not the erb?

You have different number of open “<div>” (5) and closed “</div>” (6) tags

Thanks for the reply @thebravoman, I ran into the same problem, had an extra </div> which was breaking loading Stimulus controllers on that page, but the exact same code worked on other pages. :+1: