4

Is it possible to apply a CSS class to the <body> tag of an HTML document?

I have so far been attempting something as such:

document.getElementsByClassName("body").add("cssClass");

The hope is to apply a filter over the entire DOM as to darken the page at specific times, but keep all functionality of the DOM itself.

7 Answers 7

7

Or, shorter: document.body.className = 'classname';

As suggested by Gaby, to avoid replacing of already applied class(es):

document.body.classList.add('classname')
1
  • 2
    Your current code will replace any other class currently applied on the body. Better use document.body.classList.add('classname') Dec 21, 2017 at 22:56
6

Nobody talks about there exist a toggle property.

document.body.classList.toggle("dark-mode");
1
  • I wish this worked but it doesn't appear to, at least for me.
    – Josh
    Mar 2, 2022 at 18:51
1

document.getElementsByTagName("body")[0].className = 'yo';
.yo {
  background-color: #f90;
}

1

You need to access the class list of the body - and also TagName returns a nodelist

document.getElementsByTagName('body')[0].classList.add('cssClass')
1

Almost, you need to use document.getElementsByTagName() and use like this:

document.getElementsByTagName('body')[0].classList.add('yourClass');
1

Here is an example of how to do this with ES6:

document.querySelector('body');

This codepen example shows how to toggle a class:

https://codepen.io/kylecasestack/pen/zpKZOq

4
  • 1
    What does ES6 have to do with this ? Dec 21, 2017 at 22:58
  • What if they are using a browser that may be incompatible with ES6? Dec 21, 2017 at 23:16
  • well document.querySelector is not related to ES6. ES6 is the javascript standard and has nothing to do with the DOM Api. Dec 21, 2017 at 23:19
  • 1
    Welcome to Stack Overflow @KyleSullivan thanks for helping
    – Eoin
    Jan 2, 2019 at 20:41
1
document.getElementsByTagName('body')[0].classList.add('your-class')

getElementsByTagName() returns a node list, so you'll need to access the first (and only) element.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.