Matt Martin Matt Martin - 1 year ago 182
CSS Question

jQuery add class based on page URL

I have what I think is a simple question but I can't get it to work for the life of me.

All I want to do is add some javascript to the page that adds a class to the main page container based on the URL.

Let's say I have a site at and the following html structure (loosely speaking):

<script type="text/javascript" src=""></script>
<div id="main" class="wrapper">
Blah, blah, blah

What I want to do is a script that, if the page = (for example), it adds a class to the main div. So the div would now look like:

<div id="main" class="wrapper tech">

I've loaded jquery, so I'd like to do it that way.

Answer Source

You can use window.location to get the current URL, and then switch based on that:

$(function() {
  var loc = window.location.href; // returns the full URL
  if(/technology/.test(loc)) {

This uses a regular expression to see if the URL contains a particular phrase (notably: technology), and if so, adds a class to the #main element.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download