Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle CSS class on <body> tag using vanillaJS - No JQuery

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.

like image 558
physicsboy Avatar asked Oct 28 '25 13:10

physicsboy


1 Answers

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

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

document.body.classList.add('classname')
like image 175
sinisake Avatar answered Oct 30 '25 05:10

sinisake