Javascript – compare url string and menu string then add class using jquery


I have a URL which looks like this:

I have a UL LI menu on the page:

    <li><a href="/aboutus/thegroup/test.aspx">Test</a></li>

I am having the menu on every page and would like to use jquery to check that im on that page. If i am then make the A/li bold so the user knows they are on the page.

I have tried the following:

$(document).ready(function () {
  if(window.location.href.indexOf("test")) // 
        alert("your url contains the name test");

But id like something that doesnt involve hard coding the values of the URL string. As if the user decides to add more links to the UL/LI the jquery needs to check the link and the url automatically and add a class to the LI (so that i can style it).

Hopefully thats enough infomation.

Best Solution

The issue is because the indexOf() method returns -1 when the value is not found. You need to check for that value, not coerce the result to a boolean as you currently are. Try this:

$(document).ready(function () {
    var loc = window.location.href;
    $("ul a").each(function() {
        if (loc.indexOf($(this).attr("href")) != -1) {

You would need to make the selector a bit more specific, something like #menu a