简体   繁体   中英

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 ? 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 .

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:

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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