1

So I am currently making a loading screen with only JavaScript. And I am trying to add display: none; into all elements before the load screen.

I have tried this method:

var elements = document.querySelectorAll( 'body > *' );
elements.style.display="none";

but it just came out as

Uncaught TypeError: Cannot set property 'display' of undefined
    at <anonymous>:2:23

How do I do it?

  • 4
    since elements is a NodeList, you want to iterate through it ... NodeList has a `forEach` method just for such an occasion ... `elements.forEach(element => element.style.display="none")` – Bravo Nov 24 '20 at 22:32
  • 1
    It should be an answer, @Bravo – Zsolt Meszaros Nov 24 '20 at 22:34
  • 1
    @Bravo you should make this an answer, this pretty much sums it all up – Oskar Grosser Nov 24 '20 at 22:34
  • 2
    yeah, should be the answer - or - one of the many duplicates should be the answer :p but I don't have the rep to mark as duplicate :p – Bravo Nov 24 '20 at 22:35
  • I think a cleaner solution would be to show your loader on top of the rest of the content with a zindex so it hides all other elements. And do no need to worry about hide/show anything. – T04435 Nov 24 '20 at 22:38
  • Why not just hide a parent element of all the other elements? If you wrap everything in the `body` in a `div`, you can then just hide the `div`. – Scott Marcus Nov 24 '20 at 22:38
  • 1
    Or just make not transparent overlay with loader animation on it. Then hide that only when page loads...Check solutions here: https://stackoverflow.com/questions/6091253/overlay-with-spinner Basically you show overlay and spinner first in HTML, and then hide it at end. – ikiK Nov 24 '20 at 22:39

2 Answers2

3

This is a solution using forEach method.

Pay attention! If you call it ('body *'), then all elements are styled, including all children. But if you call it like ('body >*'), then the styling is assigned to all surface elements, but not the inner elements.

var elements = document.querySelectorAll('body *');
elements.forEach(function(element) {
  element.style.display = "none";
});
<div><p>1</p></div>
<div><p>2</p></div>
<a>3</a>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25
1

Here, your elements variable isn't a specific element but a NodeList (kind of array) of elements, so you have to loop to apply your style on each element:

var elements = document.querySelectorAll( 'body > *' );
for(var i = 0; i < elements.length; i++) elements[i].style.display="none";

But be sure that your script isn't executed before your elements are loaded on the page. If it is so, you might have to wait for domready, or to use domMutationObserver API to do the stuff ;)

Janus
  • 645
  • 2
  • 7
  • 18