Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vanilla JavaScript set style on body

Tags:

javascript

Why does this not work?

Using vanilla JavaScript to set the style on body tag?

<html>    <body style="display:none;">        test    </body>    <script>        document.getElementsByTagName("body").style.display = "block";    </script> </html> 
like image 595
Hello-World Avatar asked Mar 20 '13 09:03

Hello-World


People also ask

What does body mean in JavaScript?

The document. body in javascript is a direct reference to the DOM element representing the <body> portion of the page. The $() part depends on how it is used. $ could be a variable name, and () after a variable or property name attempts to call a function stored in that variable or property.


2 Answers

Because getElementsByTagName() returns a NodeList, not a single element. Treat it as array:

document.getElementsByTagName("body")[0].style.display = "block"; 

Or even simpler in case of body:

document.body.style.display = "block"; 
like image 182
VisioN Avatar answered Sep 29 '22 20:09

VisioN


If you want the body tag you can simply use document.body. See the demo.

console.time("show body"); document.body.style.display = "none";  setTimeout(function () {     console.timeEnd("show body");     document.body.style.display = "block"; }, 3000);
<h1>Hello World!</h1>
like image 43
Aadit M Shah Avatar answered Sep 29 '22 18:09

Aadit M Shah