Javascript 如何在没有 jQuery 的情况下向 <html> 元素添加类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7388626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:04:49  来源:igfitidea点击:

How do I add a class to the <html> element without jQuery?

javascriptclass

提问by user940633

How do I add the class name "foo" to the root <html>element withoutusing jQuery (or a similar library)?

如何在使用 jQuery(或类似库)的情况下将类名“foo”添加到根<html>元素?

回答by Oliver

You can usethe classListto access an element's list of classes.

您可以使用班级列表访问类元素的列表。

document.documentElement.classList.add('my-awesome-class');

document.documentElement.classList.remove('my-awesome-class');

document.documentElement.classList.contains('my-awesome-class');

回答by Quentin

Just get the element and append to the list of classes.

只需获取元素并附加到类列表中即可。

document.documentElement.className += " foo";

回答by Igor Krupitsky

AddClass(document.documentElement, 'my-awesome-class', true); //add
AddClass(document.documentElement, 'my-awesome-class', false); //remove

function AddClass(o,c,bAdd){
    var list = o.className.split(" ");
    if (list.indexOf(c)!==-1){
        if (!bAdd) delete list[list.indexOf(c)];
    }else{
        if (bAdd) list[list.length] = c;
    }
    o.className = list.join(" ");
}