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

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.

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.

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.

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

main nav bar

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:

Hope that’s useful!


Written by Stephen Moon
email: stephen at

Leave a Reply

Your email address will not be published. Required fields are marked *