How can I dynamically add a class to 'body' using JavaScript only for the home page?

StackOverflow https://stackoverflow.com/questions/22124933

  •  18-10-2022
  •  | 
  •  

I added this to the head, but it's not working:

<script>
var xpathname = (window.location.pathname);
if (xpathname ==('/')) {
$('body').addClass('home');
}
</script>

The site is here: http://xotdr.unxpr.servertrust.com/

Volusion doesn't allow developers to code freely so there are a lot of workarounds that I need to implement, unfortunately.

Edit: I want the class to show only on the home page body.

有帮助吗?

解决方案

Since you added this to the head you need to execute this snippet when body tag is available:

$(function() {
    var xpathname = window.location.pathname;
    if (xpathname == '/') {
        $('body').addClass('home');
    }
});

其他提示

<script>
    var bodyclass=document.createAttribute("class");
    bodyclass.value="home";
    document.getElementsByTagName("body")[0].setAttributeNode(bodyclass);
</script>

Give this a try

var b = document.getElementsByTagName('body')[0];
b.className += 'home';

I know it's a old post, but the question will remain useful.

var xpathname = (window.location.pathname);
var ndeBody = document.getElementsByTagName("body")[0];
if (xpathname ==('/')) {
    ndeBody.classList.toggle("home");
}
else{
    ndeBody.classList.toggle("home");
}

When I go to that URL you have syntax error:

 Uncaught ReferenceError: x$ is not defined

e.g. you want to delete the x in x$('body').addClass('home');

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top