简体   繁体   中英

JavaScript TypeError: Cannot read property 'style' of null

I have JavaScript code and below line has problem.

if ((hr==20)) document.write("Good Night"); document.getElementById('Night).style.display=''

ERROR

Uncaught TypeError: Cannot read property 'style' of null at Column 69

My div tag details are:

    <div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;"></div>

Complete JavaScript:

    <script language="JavaScript">
    <!--
    document.write("<dl><dd>")
    day = new Date()
    hr = day.getHours()
    if ((hr==1)||(hr==2)||(hr==3)||(hr==4) || (hr==5)) document.write("Should not you be sleeping?")
    if ((hr==6) || (hr==7) || (hr==8) || (hr==9) || (hr==10) || (hr==11)) document.write("Good Morning!")
    if ((hr==12)) document.write("Let's have lunch?")
    if ((hr==13) || (hr==14) || (hr==15) || (hr==16) || (hr==17)) document.write("Good afternoon!")
    if ((hr==18) || (hr==19)) document.write("Good late afternoon!")
    if ((hr==20)) document.write("Good Night"); document.getElementById('Night').style.display=''
    if ((hr==21)) document.write("Good Night"); document.getElementById('Night').style.display='none'
    if ((hr==22)) document.write("Good Night")
    if (hr==23) document.write("Oh My! It's almost midnight!")
    if (hr==0) document.write("Midnight!<br>It is already tomorrow!") document.write("</dl>")
    //--->
    </script>

Can someone help me?

In your script, this part:

document.getElementById('Noite')

must be returning null and you are also attempting to set the display property to an invalid value. There are a couple of possible reasons for this first part to be null .

  1. You are running the script too early before the document has been loaded and thus the Noite item can't be found.

  2. There is no Noite item in your HTML.

I should point out that your use of document.write() in this case code probably signifies a problem. If the document has already loaded, then a new document.write() will clear the old content and start a new fresh document so no Noite item would be found.

If your document has not yet been loaded and thus you're doing document.write() inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite item.

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write() statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).


In addition, setting the display property to "display" doesn't make sense to me. The valid options for that are "block" , "inline" , "none" , "table" , etc... I'm not aware of any option named "display" for that style property. See here for valid options for teh display property.

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/ . That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.


PS I should point out that your lack of braces for your if statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.


I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/ . Here's a list of the changes I made:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added var declarations to your variables (a good habit to always use).
  3. The if statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every if statement so it absolutely clear which statements are part of the if/else and which are not.
  5. I've properly closed the </dd> tag you were inserting.
  6. I've changed style.display = ''; to style.display = 'block'; .
  7. I've added semicolons at the end of every statement (another good habit to follow).

The code:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você não<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almoçar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

This happens because document.write would overwrite your existing code therefore place your div before your javascript code. eg:

CSS:

#mydiv { 
  visibility:hidden;
 }

Inside your html file

<div id="mydiv">
   <p>Hello world</p>
</div>
<script type="text/javascript">
   document.getElementById('mydiv').style.visibility='visible';
</script>

Hope this was helpful

Your missing a ' after night. right here getElementById('Night

For me my Script tag was outside the body element. Copied it just before closing the body tag. This worked

enter code here

<h1 id = 'title'>Black Jack</h1>
<h4> by Meg</h4>

<p id="text-area">Welcome to blackJack!</p>
<button id="new-button">New Game</button>
<button id="hitbtn">Hit!</button>
<button id="staybtn">Stay</button>

 <script src="script.js"></script>

simply I think you are missing a single quote in your code

if ((hr==20)) document.write("Good Night"); document.getElementById('Night"here").style.display=''

it should be like this

if ((hr==20)) document.write("Good Night"); document.getElementById('Night').style.display=''

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

let clock = setInterval(() => {
        clearInterval(clock)
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)

Your source to the script may be in the incorrect place. Put the link to your JS page UNDER the /body.

    </body>
    <script src="Index.js"></script>
    </html>

The possible reason behind the error is that the JavaScript runs much earlier than the objects it requires from the webpage are loaded. The below codes will certainly solve the issues.

if ( document.getElementById('Night) )
    document.getElementById('Night).style.display=''";

It is always a good practice to check for the existence of a DOM object before calling an action on the Object.

Add "defer" to your line in HTML

 <script src="Index.js" defer ></script>

It'll load the JS AFTER the page has been loaded.

this can also happen where you write an html tag after loading js script file

 <div id="MyBox" class="box"></div>
<script src="Script.js"></script>

now if i try to get MyBox and log it in console i

const box = document.getElementById("MyBox");

will get this kind of error

Uncaught TypeError: Cannot read properties of null (reading 'style')
at Script.js:519:5

so try moving your external js tags

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