Typeerror: Cannot set Property 'innerHTML' of null

Asked

Viewed 1,908 times

0

Good morning/Afternoon/Evening,

I have done and remade several times the same process following the specifications necessary to work(name with the correct id, import the id in js and put it out of function so it can be used everywhere within the code, define a name, use the name to instantiate the objects, apply innerHTML to send a value, put the + before the value not to delete what was before, I even made a window.Alert to ensure that the values were actually being generated) and still the error persists.

(The intention is to play the pro log values, the name under the button is just a placeholder for another function)

var log = document.getElementById("lognome");

function gerarNome(){
var RandomNames = {
    firstNames: [
      'Vinicius',
      'Talita',
      'Maria',
      'João',
      'José',
      'Marcos'
    ],
    middleNames: [
      'Costa',
      'Araújo',
      'Rodrigues',
      'Pereira',
      'Soares'
    ],
    lastNames: [
      'Pires',
      'Alves',
      'Álvares',
      'Moreira',
      'Ferreira'
    ],
    generate:function(quantity){
      var maxNames = this.firstNames.length * this.middleNames.length * this.lastNames.length;
      if (quantity > maxNames) {
        throw "Quantity greater than possible matches. Possible matches: "+maxNames;
      }
      var names = [];
      while ( names.length < quantity ) {
        var name = "";
        var first = Math.floor( Math.random() * this.firstNames.length );
        name+= this.firstNames[first];
        var middle = Math.floor( Math.random() * this.middleNames.length );
        name+= " "+this.middleNames[middle];
        var last = Math.floor( Math.random() * this.lastNames.length );
        name+= " "+this.lastNames[last];
        
        if (names.indexOf(name)==-1) {
          names.push(name);
        }
      }
      return names;
    }
  };
  
  try {
    var names = RandomNames.generate(10);
    for (var i=0; i<names.length; i++) {
        window.alert(names[i]);
        log.innerHTML = + names[i];  
    //   document.write(names[i]+'<br/>');
    }
    // document.write('<br /><strong>Total names:</strong> '+names.length);
  } catch (e) {
    document.write(e);
  }
}

function limparlog(){
    log.innerHTML = "";
}
.btnr{
    clear: both;
    background: rgba(26,26,64,1) ;    
    border: none;
    color: white;
    padding: 10px 20px;
    text-align: center;
    font-size: 16px;
    box-shadow: 3px 2px 3px -2px rgba(54,54,54,1);

}

.btnr:hover{
  outline: none;
    cursor:grab;
    background-color:  rgba(24,24,58,1); /* Green */
    border: none;
    color: white;
    padding: 10px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    box-shadow: 3px 2px 3px -2px rgba(54,54,54,1);

}

.log{
  font-size: 14px;;
  cursor: default;
  scrollbar-color: #000000;
  border-color: #00000000;
  color: aliceblue;
  background-color: #00000046;
  font-size: 2em;
  overflow-y: scroll;
  resize: none;
  width: 750px;
  height: 250px;
  margin: 25px;
}

.btnl{
  position: relative;
  background: #141414;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  font-size: 16px;
  box-shadow: 3px 2px 3px -2px rgba(54,54,54,1);

}
<!DOCTYPE html>
<html>
<head>
    <!--Styles-->
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
    <!--Scripts-->
    <script language="javascript" src="Scripts/script.js"></script>
    <script language="javascript" src="Scripts/index.js"></script>
    <!--Meta-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>
        Gerador de Nomes
    </title>
</head>

<body class="bg">
    <!-- <header class="top">
        <div>
                <a class="navbtn" href="./index.html"></i><h2 class="main"></i>Site do RPG<i class="fas fa-dice-d20" id="icon"></i></h2></a>

                <a class="navbtn" href="./menu.html"><p class="main">Menu</p></a>
                
                <a class="navbtn" href="./contador.html"><p class="main">Contador</p></a>
                
                <a class="navbtn" href="./dados.html"><p class="main">Dados</p></a>
                
                <a class="navbtn" href="./fichas.html"><p class="main">Fichas</p></a>

                <div class="search">
                    <a class="fas fa-search" id="icon" href="http:\\www.google.com"></a>
                </div>
        </div>
    </header>

    <div> 

            <div class="sidemenudados"> 

                    <div class="sidemenucontent"> 

                        <a href="./menu.html">
                            <h2><i id="icond" class="fas fa-calculator" id="icon"></i></h2>
                        </a>

                        <a href="./contador.html">
                            <h2><i id="icond" class="fas fa-clock" id="icon"></i></h2>
                        </a>

                        <a href="./dados.html">
                            <h2><i id="icond" class="fas fa-dice-d20" id="icon" ></i></h2>
                        </a>

                        <a href="./fichas.html">
                        <h2><i id="icond" class="fas fa-address-card" id="icon"></i></h2>
                        </a>

                        <h2><i id="icond" class="fas fa-cheese" id="icon"></i></h2>

                    </div>
                </div> -->

            <div class="menudsgn"> <!--Casewrapping-->
                    <div class="center"> <!--Centering Prop.-->
                            <div class="middle"> <!--Module Top-->
                                <div class="aligname"> <!--Interior Alignment-->

                                    <h1>Gerador de Nomes</h1>
                                    <button class="btnr" onclick="gerarNome()" id="generate-name">Gerar</button>
                                    <h2>
                                    <span class='color' id='color-name'>Geralt</span>
                                    <span class='surname' id='sur-name'>de Rivia</span>
                                    </h2>

                                </div>
                            </div>

                            <div class="middle2"> <!--Module Bottom-->
                                <label class="logtext">Log de Nomes</label>
                                <textarea spellcheck="false" id="lognome" class="log" readonly></textarea>
                                <button class="btnl" onClick="limparlog()" id="limparlog">Limpar Log</button> 
                            </div>
                    </div>   
            </div>
    
</body>
</html>

  • Which line gives this error? When running your code, no error is shown.

  • No line is being pointed (VS Code usage), the error is only captured by var "e" and is shown with Document.write() replacing the entire page with the error instead of the list of names ref: link

  • Vc is running the script before HTML, so it does not find the element #lognome.

2 answers

0

Opa!

There in your JS, in that stretch:

try {
var names = RandomNames.generate(10);
for (var i=0; i<names.length; i++) {
    window.alert(names[i]);
    log.innerHTML += names[i];  
//   document.write(names[i]+'<br/>');
}
// document.write('<br /><strong>Total names:</strong> '+names.length);

}

Fix the line

log.innerHTML = + names[i];

for

log.innerHTML += names[i];  
  • It is good programming practice to decrease the " x = x + y" to "x += y", but unfortunately it does not solve the reference error

  • Take a look at this Pencode https://codepen.io/anon/EJZEzm. It was the only change I made and it worked. In addition, you also have to load this javascript at the end of the HTML code, because as already answered up there, if you load the JS before the DOM, the code will not be able to find the Document.getElementById("lognome");

0


You are loading the script into <head>, with that the line:

var log = document.getElementById("lognome");

Couldn’t find the element #lognome which has not yet been loaded, thus giving error in reference, which will be null.

To fix this, you can assign the value to the variable log after the DOM is carried, in this way:

var log; // declara a variável sem nenhum valor atribuído
document.addEventListener("DOMContentLoaded", function(){
   // após o DOM ter sido carregado,
   // atribui o elemento à variável
   log = document.getElementById("lognome");
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.