William Martin
William Martin

Reputation: 118

How to set multiple classes to an element with a conditional

This EJS scriptlet

<li class=<%= (path==='about') ? 'active main-header--nav-item' : 'main-header--nav-item' %>>about</li>

renders on the page as this:

<li class="active" main-header--nav-item="">about</li>

when I'm trying to make it output as:

<li class="active main-header--nav-item">about</li>

i.e. two classes. I'm assuming I'm making a simple error with syntax in the conditional but I can't seem to fix it.

Upvotes: 0

Views: 136

Answers (1)

Terry
Terry

Reputation: 66133

That's because in your EJS template you are not enclosing the class list with "". When that is the case, a whitespace character will end up being interpreted as the end of the attribute. Your template above actually renders into this:

<li class=active main-header--nav-item>about</li>

The browser will then interpret the class to have the value of active, and that main-header--nav-item is just some custom HTML attribute, hence your observed output of:

<li class="active" main-header--nav-item="">about</li>

You should be doing this instead:

<li class="<%= (path==='about') ? 'active main-header--nav-item' : 'main-header--nav-item' %>">about</li>

Upvotes: 1

Related Questions