Hotwire Discussion

Multiple css classes using the css class api?

I tried searching but didn’t find an answer. Is it possible to have a space delimited list of multiple css class names for the stimulus js css class api? I’m only able to get it working with one css class name.

e.g. data-sample-foo-class="one-item-css-class"

But I want to use two or more css classes. something like
data-sample-foo-class="class-one class-two"

Is there a way to do this elegantly? I’m currently assigning each class individually and it’s cumbersome.

1 Like

Thanks @nodalailama i saw your deleted message. That is also what I am currently doing :slight_smile: but I was hoping there was a better way.

Can someone repost the suggested solution for comparison?


The suggestion was to do like the stimulus’s doc recommend:


So just list two data attributes for 2 class declaration.


Stimulus does not restrict you from assigning multiple classes to a class variable and element.classList.add can take multiple classes as separate parameters.

element.classList.add('one', 'two', 'three')

Using the spread operator you can covert an array into multiple parameters, something like:

<form data-controller="search"
      data-search-loading-class="one two three">
export default class extends Controller {
  static classes = [ "loading" ]

  loadResults() {
    this.element.classList.add(...this.loadingClass.match(/[^ ]+/g))

FYI, I used match with regex instead of split to handle cases where there might be 2 or more spaces.

const classes = 'one       two      three';
classes.split(' ');
//=> (14) ["one", "", "", "", "", "", "", "two", "", "", "", "", "", "three"]
classes.match(/[^ ]+/g)
//=> (3) ["one", "two", "three"]

There was PR about this a few months ago. For now, using the match operator as @tleish mentions is the only way I got it working.

Anyone know what’s the reason the suggested ...this.loadingClasses was not implemented?

The team merged the PR and released it in v3.0.0-beta.1 release.