简体   繁体   English

如何用 JavaScript 隐藏所有 div?

[英]How to hide all divs with JavaScript?

I am wondering how I can hide all divs on the page only using JavaScript, I cannot use jQuery. Is there a way to do this without using the arrays that comes with document.getElementByTag ?我想知道如何仅使用 JavaScript 隐藏页面上的所有 div,我不能使用 jQuery。有没有办法在不使用document.getElementByTag附带的 arrays 的情况下执行此操作? Or if there is not, could you show me how to hide all?或者,如果没有,您能告诉我如何隐藏所有内容吗?

Use getElementsByTagName() to get a list of all div elements, and then set their CSS display property to none . 使用getElementsByTagName()获取所有div元素的列表,然后将其CSS display属性设置为none

var divs = ​document.getElementsByTagName("div");​
for (var i = 0; i < divs.length; i++) {
  divs[i].style.display = 'none';        
}

DEMO . 演示

You will need to use document.getElementsByTagName , and then use a for loop to process all of the elements: 您将需要使用document.getElementsByTagName ,然后使用for循环来处理所有元素:

var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
  divs[i].style.display = "none";
}

Just to put out a totally different solution here. 只是在这里提出一个完全不同的解决方案。

You could set a CSS class to your body, like this 你可以为你的身体设置一个CSS类,就像这样

body.hideDivs DIV {

    display: none;

}

document.body.className = "hideDivs";

But this would hide everything inside those divs also, which might not be what you are going for here. 但这也会隐藏这些div中的所有内容,这可能不是你想要的。

或者改用它,它既快捷又简单:

document.getElementsByTagName('div')[0].style.display = 'none'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM