logo
podcast Podcast
get help Get Unstuck

Why does Alpine ignore binding to the same attribute multiple times?

Hint, it's not an Alpine issue

Joel Clermont
Joel Clermont
2025-06-26

Consider this sanitized code sample shared in the Mastering Laravel community:

<a id="toggle_btn"
   x-data="{ rotated: false }"
   @click="rotated = !rotated"
   :class="sidebarIsOpen ? '' : 'opacity-[0] h-0 w-0'"
   :class="rotated ? 'rotate-180' : ''"
   class="bunch of other classes here"
>
    <i class="ti ti-menu-deep"></i>
</a>

Here was the question: Why is the rotate-180 class never being applied, even though rotated is being toggle to true successfully?

The short answer is that you can't have :class on the same element more than once. The second instance is completely ignored.

But why?

Consider this pure HTML example, no Alpine involved:

<!DOCTYPE html>
<html>
  <body>
    <div class="first" class="second"></div>
  </body>
</html>

If you look at the parsed HTML in the dev tools Elements tab, this is what you will see:

<!DOCTYPE html>
<html>
  <body>
    <div class="first"></div>
  </body>
</html>

Notice the second class attribute is completely gone. It's stripped out when the HTML is parsed.

This is documented in the HTML spec, where it states:

There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.

So whether the attribute is class, :class or data-whatever, you can only have one of them on the same element, and additional attributes are thrown away.

As a side point, it's fine to have class and :class on the same element because they are not the same attribute, even though they are conceptually treated the same by Alpine.

So how can we achieve the desired outcome? The solution is to use the array syntax like this:

<a id="toggle_btn"
   x-data="{ rotated: false }"
   @click="rotated = !rotated"
   :class="[
    sidebarIsOpen ? '' : 'opacity-[0] h-0 w-0',
    rotated ? 'rotate-180' : ''
   ]"
   class="bunch of other classes here"
>
    <i class="ti ti-menu-deep"></i>
</a>

Here to help,

Joel

P.S. We'd love to have you join us in the Mastering Laravel community as well. Very low cost, and quite a valuable resource for working developers.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.