I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues when there are multiple words in the category name. Here is the code snippet:
( window.onload=function() {
let cat = document.querySelector('.cats').lastElementChild.textContent;
let body = document.querySelector('body');
if(cat.indexOf(' ') >= 0) {
cat.replace(' ','-');
body.classList.add(cat.toLowerCase());
} else {
body.classList.add(cat.toLowerCase());
}
})();
For example, if the category is "dentist," it gets added as a string to the body tag. However, if the category is "General Doctor," it doesn't work properly.
I'm using functions.php to call this function only when it's a post by using if_single().
I tried using replace() to replace the space with a dash, but I seem to be implementing it incorrectly.
Is there a way I can transform something like "General Physician" into a string like "general-physician" so that it can be added as a class to the body tag?