0

I've seen many topics for adding a class or id to body but my issue has to do with the root url, and other urls with a trailing slash.

I'm trying to add a unique class or id to body for each page based on the URL, with the option of adding one of your choice for the root, but it always adds that one to every page due to the trailing slash in the URL.

This is what I've got

$(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".php","");
if(truePath === '') {
    $('body').attr('id', 'home'); // set to 'home' for the root
}
else {
    $('body').attr('id', truePath);
}
});

The results

Root: <body id="home">

Interior page (/work/projectname/): <body id="home">

I'm getting the id "home" for every page. I just want "home" on the root and no other pages. And ideally id "projectname" for the interior(s).

I've determined that the trailing slash of my interior page URLs is causing this. I think some regex problem. I also tried some htaccess to remove the trailing slash with no luck so that's another conversation.

I'm wondering if editing (/.*\/(.*)$/)[1] for this to work?

Thank you.

Ira
  • 87
  • 7
  • Your code is working for me. But I always do it like this to get the truepath: `var truePath = location.pathname.substring(location.pathname.lastIndexOf("/") + 1).replace('.php','');` – Mark S Dec 09 '13 at 00:36
  • It's working for you as in the root/home page has body id="home" and no other pages have that body id? I tried your truepath edit and my results are still the same; body id="home" on every page. Thank you. – Ira Dec 09 '13 at 00:49
  • Yes with the correct `` id. I think ensure that jQuery is included in all this pages. And if you're using jQuery 1.6 higher try switching to `prop()`. – Mark S Dec 09 '13 at 01:28
  • Are you hitting direct html/php pages or directories? My links from the main page go to /work/projectname/ and that trailing slash is I believe what's causing the problem. If I go directly to /work/projectname/index.php it works fine. – Ira Dec 09 '13 at 01:39

0 Answers0