使用 Javascript 将类添加到 <html>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13980982/
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
Add class to <html> with Javascript?
提问by Brandon Lebedev
How do you add a class to the <html>root element using Javascript?
如何<html>使用 Javascript向根元素添加类?
回答by Kevin Boucher
Like this:
像这样:
var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)
root.setAttribute( 'class', 'myCssClass' );
Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)
或者使用它作为你的“setter”行来保留任何以前应用的类:(感谢@ama2)
root.className += ' myCssClass';
Or, depending on the required browser support, you can use the classList.add()method:
或者,根据所需的浏览器支持,您可以使用以下classList.add()方法:
root.classList.add('myCssClass');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classListhttp://caniuse.com/#feat=classlist
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist
UPDATE:
更新:
A more elegant solution for referencing the HTMLelement might be this:
引用HTML元素的更优雅的解决方案可能是这样的:
var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
// root.classList.add('myCssClass');
//
回答by c24w
This should also work:
这也应该有效:
document.documentElement.className = 'myClass';
兼容性。
Edit:
编辑:
IE 10 reckons it's readonly; yet:
IE 10 认为它是只读的;然而:


Opera works:
歌剧作品:


I can also confirm it works in:
我还可以确认它适用于:
- Chrome 26
- Firefox 19.02
- Safari 5.1.7
- 铬 26
- 火狐 19.02
- Safari 5.1.7
回答by aebersold
回答by ama2
You should append class not overwrite it
你应该追加类而不是覆盖它
var headCSS = document.getElementsByTagName("html")[0].getAttribute("class") || "";
document.getElementsByTagName("html")[0].setAttribute("class",headCSS +"foo");
I would still recommend using jQuery to avoid browser incompatibilities
我仍然建议使用 jQuery 来避免浏览器不兼容
回答by Tom Esterez
document.documentElement.classList.add('myCssClass');
classListis supported since ie10: https://caniuse.com/#search=classlist
classList从 ie10 开始支持:https://caniuse.com/#search=classlist
回答by Roos Bautista
With Jquery... You can add class to html elements like this:
使用 Jquery...您可以将类添加到 html 元素,如下所示:
$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');
$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');
nameclassoridno point or # at the beginning
nameclassorid没有点或#开头

