Ember.js How to set classes

Quang Nguyen
quangtn0018
Published in
2 min readSep 3, 2018

Relative to using pure HTML and JavaScript to set or add css classes to elements, Ember.js has a more elegant way of setting classes to elements or components.

For example, we have something like this:

// list1.css
.hideList {
display: none
}
.showList {
display: block
}
// list1.html
<li id='list' class='hideList' onclick='showList()'>
<ul>Apple</ul>
<ul>Orange</ul>
<ul>Banana</ul>
</li>

And lets say I wanted to set a ‘showList’ class when I click on the <li> element. In pure HTML and JavaScript, the conventional and simple way you would do it is this:

// list1.js
<script>
function showList() {
let listTag = document.getElementById('list');
listTag.className += 'showList'
}
</script>

Now, that didn’t take a lot of code to do what we wanted, which was adding a class to an element. But we had to look through the DOM and find the element’s ID in order to modify it.

Consider Ember’s way of doing this:

// list2.css
.hideList {
display: none
}
.showList {
display: block
}
// same html code that we had before but in a hbs file
// list2.hbs
<li class='hideList {{if isShowingList "showList"}}' {{action 'showList'}}>
<ul>Apple</ul>
<ul>Orange</ul>
<ul>Banana</ul>
</li>
// list2.js
import Ember from 'ember';
Ember.route.extend() {
isShowingList: false,
actions: {
showList() {
this.toggleProperty('isShowingList')
}
}
}

With Ember’s conditionals, this code became much more logical, readable, and maintainable when another developer comes and reads this code. Compared to the pure HTML and JavaScript way, the Ember’s solution just flows better and is easier to read. If I was a developer who was asked to look at this code, I would immediately understand that by looking at the class, if the variable isShowingList is true, only then will my <li> element would contain the ‘showList’ css style.

Recently, I have been learning and using Ember.js and I’ve come across many scenarios where I have used this technique to set classes. I have done it both ways and I have to say, Ember has done well on that front.

I’m always learning new frameworks for different clients at work and techniques to improve my coding abilities, so if you guys have any suggestions or comments to further my learning process, feel free to comment below!

--

--