简体   繁体   中英

Cannot read property 'innerHTML' of null

I am beginner in javascript.

js file

         var msgErrorPalletizedWeight = document.getElementById('msgError');
         function palletizedWeightValidation() {
              console.log("hello");
/*ERROR*/     msgErrorPalletizedWeight.innerHTML += ("Please enter all the values marked with *");
         }

HTML

<head runat="server">
   <title></title>
   <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
   <script src="Scripts/file.js" type="text/javascript"></script>
</head>
<body>
    <p id="msgError"></p>
    <asp:Button ID="btnSubmitPalletized" runat="server" Text="Submit" 
                   OnClientClick="palletizedWeightValidation()" />
</body>

ERROR

Cannot read property 'innerHTML' of null

I searched many sites before asking here, they all recommending to check for null before validations which I can do but my problem here is I want to add some text to the p tag as you can see.. How to achieve that? I even tried appending, thought it might solve the problem. I know this is a silly mistake because there are many posts on this... the thing is that I cant understand where I am going wrong.

Please help.

You are trying to access the element of html when it is not ready , put the statement in event function to get the element in function palletizedWeightValidation .

      function palletizedWeightValidation() {
              var msgErrorPalletizedWeight = document.getElementById('msgError');
              console.log("hello");
/*ERROR*/     msgErrorPalletizedWeight.innerHTML += ("Please enter all the values marked ith *");
         }

EDIT To stop postback , you need to return false from javascrip function.

 <asp:Button ID="btnSubmitPalletized" runat="server" Text="Submit" 
                   OnClientClick="return palletizedWeightValidation()" />


      function palletizedWeightValidation() {
              var msgErrorPalletizedWeight = document.getElementById('msgError');
              console.log("hello");
/*ERROR*/     msgErrorPalletizedWeight.innerHTML += ("Please enter all the values marked ith *");
              return false; // returning true will cause postback.
         }

The important thing is when your js file gets executed. If you load js file inside head tag, your file will be executed before DOM is created. That means, document.getElementById function returns null.

The error you are getting is caused because you are trying to read an attribute of a NULL object. This means that your line:

var msgErrorPalletizedWeight = document.getElementById('msgError');

is not finding any elements on your page.

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