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