JQuery to add <body> class, need a little more help

Danny Englander picture Danny Englander · Nov 9, 2011 · Viewed 8.3k times · Source

I have this snippet of code to parse the URL and add a class to the <body>tag of my HTML page.

var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, " ");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace(" ","");
var newClass = pathSlashesReplacedNoFirstDash.replace(/(\.[\s\S]+)/ig, "");

$("body").attr("class",newClass);
if ( $("body").attr("class") == "")
{
$("body").addClass("class");
}

The issue I am having is that it deletes existing body classes already there. Instead, I would like to append to whatever body classes exist and not overwrite.

Answer

Smamatti picture Smamatti · Nov 9, 2011

Use this:

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

instead of

$("body").attr("class",newClass);

This is a setter: $("body").attr("class",newClass); which sets the class to the newClass and does not append it.