如何使用vanillaJS在标签上切换CSS类 - 没有JQuery

时间:2022-11-27 21:10:46

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

是否可以将CSS类应用于HTML文档的标记?

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.

希望在整个DOM上应用过滤器,以便在特定时间使页面变暗,但保留DOM本身的所有功能。

6 个解决方案

#1


5  

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

或者,更短:document.body.className ='classname';

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

正如Gaby建议的那样,为了避免替换已经应用的类:

document.body.classList.add('classname')

#2


1  

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

#3


1  

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

您需要访问正文的类列表 - 并且TagName还返回节点列表

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

#4


1  

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

几乎,您需要使用document.getElementsByTagName()并使用如下所示:

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

#5


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.

getElementsByTagName()返回一个节点列表,因此您需要访问第一个(也是唯一的)元素。

#6


0  

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

以下是如何使用ES6执行此操作的示例:

document.querySelector('body');

This codepen example shows how to toggle a class:

此codepen示例显示如何切换类:

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

#1


5  

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

或者,更短:document.body.className ='classname';

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

正如Gaby建议的那样,为了避免替换已经应用的类:

document.body.classList.add('classname')

#2


1  

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

#3


1  

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

您需要访问正文的类列表 - 并且TagName还返回节点列表

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

#4


1  

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

几乎,您需要使用document.getElementsByTagName()并使用如下所示:

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

#5


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.

getElementsByTagName()返回一个节点列表,因此您需要访问第一个(也是唯一的)元素。

#6


0  

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

以下是如何使用ES6执行此操作的示例:

document.querySelector('body');

This codepen example shows how to toggle a class:

此codepen示例显示如何切换类:

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