简体   繁体   中英

Uncaught TypeError: Cannot read property 'style' of null error javascript

when i open my site index.html and i go on the console I get this error: Uncaught TypeError: Cannot read property 'style' of null at index-login.js:22

I already read this question but it still doesn't work.

var keyRequireBoolean0 = keyInput.includes('anon')
if (keyRequireBoolean0 == true) {
    var keyRequireBoolean1 = keyInput.includes('sup')
    if (keyRequireBoolean1 == true) {
        document.getElementById("validKeyText").style.visibility = "visible";
    } else {
        document.getElementById("invalidKeyText").style.visibility = "visible";
    }
} else {
    document.getElementById("invalidKeyText").style.visibility = "visible";
}}

console.log('Defined Function')
document.getElementById('validKeyText').style.visibility="collapse"; 
      // here i get this error: Uncaught TypeError: Cannot read property 'style' of null at index-login.js:22
document.getElementById('invalidKeyText').style.visibility="collapse";

HTML PART BELOW

  <form class="box" action="index.html" method="post">
  <h1>Enter You Key Below</h1>
  <input type="password" id="keyInputBox" placeholder="Key">
  <input type="submit" onclick="validate()" value="Check">
  <a id="validKeyText" href="batch-obfuscator.html">Key Accepted! Click here to continue.</a>
  <a id="invalidKeyText">Invalid Key, Try Again.</a>
  </form>

CSS PART BELOW

#validKeyText{
  color: rgb(0, 255, 64);
  font-size: 11px;
}
#invalidKeyText{
  color: rgb(145, 0, 0);
  font-size: 11px;
}

how can I fix?

I tried running your code, and it works fine for me when the order is correct.

Make sure your javascript comes after the html, so that when you run any document.getElementById it actually returns an element from the DOM instead of null, which it can then apply the needed styles on.

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