Search code examples
alpine.js

Remove existing class


Let's say I have this HTML element with an Alpine.js class binding:

<li id="123" 
    :class="$el.id === activeId ? 'bg-pink-900 text-white' : 'bg-gray-100'">Foo</li>

This works fine as long as my server rendered HTML doesn't look like this:

<li id="123"
    class="bg-pink-900 text-white"
    :class="$el.id === activeId ? 'bg-pink-900 text-white' : 'bg-gray-100'">Foo</li>

Now, when activeId doesn't match, bg-pink-900 text-white isn't removed from the element which has been rendered server side at first.


Solution

  • The attribute :class in AlpineJs has a special behavior: it preserves the existing classes on an element.
    The reason is because there are generally classes that you want to keep regardless of the condition.

    The solution is to remove the 'static' class assignement:

    <li id="123"
        :class="$el.id === activeId ? 'bg-pink-900 text-white' : 'bg-gray-100'"
    >
        Foo
    </li>
    

    Here the explanation of this behavior

    You may also take a look to the Class object syntax:

    <li id="123"
        :class="{'bg-pink-900 text-white': $el.id === activeId,
                 'bg-gray-100': $el.id !== activeId
                }"
    >
        Foo
    </li>