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.
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.