Adding and Removing Classes from Elements

I am working on a Bootstrap 3 based project where I have a nav bar placed just under a big jumbotron. Here’s how it looks:

Looks OK, right, but the problem was when I first added it, I’d placed this code in the page: _Layout.cshtml

1
2
3
4
5
6
<ul class="nav nav-pills nav-justified">
<li class="active"><a href="/Home/">Home</a></li>
<li><a href="/Home/FAQ">FAQ</a></li>
<li><a href="/Home/Runs">The Runs</a></li>
<li><a href="/Home/Donate">Donate</a></li>
</ul>

As you can imagine, that would mean that no matter which of the four pages you visited, be that FAQ, The Runs or Donate, it would still show Home as being highlighted. Not quite what I intended. What I really needed was that as soon as I clicked on a page, it would make that tab active and the others, inactive. Here’s how I did it. Firstly, I removed the class reference from the first tab, Home. What do you think would happen if I didn’t? Can more than one tab be active at the same time? Actually, yes! Anyway, let’s scratch that.

1
2
3
4
5
6
<ul class="nav nav-pills nav-justified">
<li><a href="/Home/">Home</a></li>
<li><a href="/Home/FAQ">FAQ</a></li>
<li><a href="/Home/Runs">The Runs</a></li>
<li><a href="/Home/Donate">Donate</a></li>
</ul>

The next step was to name each element so that I could refer to each individually. That’s what you can see in the next listing and is pretty straight-forward.

1
2
3
4
5
6
<ul class="nav nav-pills nav-justified">
<li class="active" id="home"><a href="/Home/">Home</a></li>
<li id="faq"><a href="/Home/FAQ">FAQ</a></li>
<li id="runs"><a href="/Home/Runs">The Runs</a></li>
<li id="donate"><a href="/Home/Donate">Donate</a></li>
</ul>

But what about making the tabs active? The trick was to add a reference to the active class. I could do that in jQuery but let’s look at how we can do that in JavaScript.

1
2
3
<script>
document.getElementById('home').classList.add('active');
</script>

Lastly, we add this to the top of each view, replacing home with whichever id is applicable leading to the following:

Hang on! Someone at the back just piped up asking about how do remove classes? That’s just another method in classList that we can use. I didn’t need it here, but for completeness, here’s an example:

1
2
3
<script>
document.getElementById('home').classList.remove('active');
</script>

Hope that’s useful!


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com