How to add an ID to every body tag with JQuery.

How to add an ID to every body tag with JQuery.

This is a quick one, more of a snippet to myself than a legitimate blog post but figured I’d put this here on the off chance this might help some other folks.

Let’s say you are dealing with a CMS or some other legacy / 3rd party system that generates the page HTML of your site in a way that is beyond your control.  You might need to get a distinct handle on certain elements of a specific page so you can style them with CSS or perform some JQuery magic. 

This little snippet will add an id of the page’s name (swapping / with –) to the body tag of every page.  This is injected into the DOM on page load so you won’t see it in regular ‘view source’, but will be able to see it with FireBug or the firefox web developers toolbar ‘view generated source’ option. 

As the inline comments say, www.blah.com/this/that/whatever.html, will become body id="this-that-whatever" or, if you are the webroot of your site, body id="home-page". Just add this in your $(document).ready(function() block …

// Duncan hack, get the entire path, turn /s to -s 

// strip extension and add that as an id to the body

// so we can target specific pages in the styles if we need to

 

// www.blah.com/this/that/whatever.html -> body id="this-that-whatever"

// or body id="home-page" if at root / 

 

var pathname = window.location.pathname;

var pathSlashesReplaced = pathname.replace(/\//g, "-");

var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace("-","");

var newID = pathSlashesReplacedNoFirstDash.replace(/(\.[\s\S]+)/ig, "");

 

$("body").attr("id",newID);

 

if ( $("body").attr("id") == "")

{

    $("body").attr("id","home-page");

}

 

If you instead wanted to add the new identifier as a class, simply use a line like:

$("body").addClass(pathSlashesReplacedNoFirstDash);

instead of

$(“body”).attr(“id”,pathSlashesReplacedNoFirstDash);

Now you can target every page with your CSS / JQuery and make everyone happy! Hooray!  This uses javascript regular expressions so may not be as super optimized as it could be using substrings, etc, but it gets the job done.

Named anchors are not sent to the web server! Who knew?