Karuvägistaja
Karuvägistaja

Reputation: 293

display = 'none' does not work in javascript

I want to hide divA and show divB. If I click a button I want to hide divB and show divA. I don't want to use JQuery.

I have troubles hiding divA when the page loads. When I click the button, the divB is hidden correctly.

I added this in the beginning of the document

<script>
    var doNotShow= document.getElementById('divA');
    doNotShow.style.display = 'none';
</script>

The thing is, it does not work. The weird thing is that when later, I try to hide divB via a button click then divB hides as it should. The divA is after the javascript part in the file.

Upvotes: 3

Views: 10575

Answers (3)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70139

I added this in the beginning of the document

You must execute document.getElementById after the element with the queried ID exists in the document, otherwise null will be returned.

You can move the script tag to the bottom of the page (or simply after those elements), or wrap it inside a window.onload handler.


It's good practice to have the <script> tags right before the closing </body> so all the elements are already present in the page and you don't need to worry about wrapping code in window.onload or DOM ready (DOMContentLoaded) handlers.

Upvotes: 8

plalx
plalx

Reputation: 43718

Your code is running before divA exists in the DOM. That's why it doesn't work.

To solve the issue with your current solution, put your script after the divA markup in the document.

However, you do not need to use JavaScript and probably shouldn't to initially hide your divA element. You can use the following CSS rule instead:

#divA { display: none; }

Upvotes: 1

honza_p
honza_p

Reputation: 2093

Javascripts are executed when they are read. If divA is defined after the script, there is nothing to execute the script on, which you will see if you use debugging tools like Firebug in Firefox or Developer Tools in Chrome (a TypeError will occur).

Upvotes: 1

Related Questions