jQuery add class based on page URL

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)) {
    $('#main').addClass('tech');
  }
});

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.

Leave a Comment