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