innertext

JavaScript innerText


I am new to JS. I'm trying to run this line of code that will save a count of numbers at each click with an embedded text. But on running it I'm having this error.

Uncaught TypeError: Cannot read properties of null (reading 'innerText')

Here is my code

JavaScript

 let saveEl = document.getElementById("save-el")
 let countEl = document.getElementById("count-el")
 let count =0

 function increment(){
     count+=1 
     countEl.innerText=count
 }                        

 function save(){
     let countStr= count + " - "
     saveEl.innerText+=countStr 
     countEl.innerText=0
     count=0
 }

HTML

<html>
<head>
<link rel="stylesheet" href="index.css">
</head>

<body>
     <h1><strong>People Entered:</strong></h1>
    <h2 id="count-el">0</h2>
<script src="index.js"></script>
<div class="container-btn">
<button id="increment-btn" onclick="increment()">INCREMENT</button>
<button id="save-btn" onclick="save()">SAVE</button>
<p id="save-el">Previous entries: </p>
</div>  
</body>


</html>

Solution

  • Try moving your <script> tag to the end of your <body>, or only run it on DOM load:

    let count = 0
    var saveEl;
    var countEl;
    
    function increment() {
      count += 1
      countEl.innerText = count
    }
    
    function save() {
      let countStr = count + " - "
      saveEl.innerText += countStr
      countEl.innerText = 0
      count = 0
    }
    
    document.addEventListener('DOMContentLoaded', e => {
      saveEl = document.getElementById("save-el")
      countEl = document.getElementById("count-el")
    })
    <h1><strong>People Entered:</strong></h1>
    <h2 id="count-el">0</h2>
    <div class="container-btn">
      <button id="increment-btn" onclick="increment()">INCREMENT</button>
      <button id="save-btn" onclick="save()">SAVE</button>
      <p id="save-el">Previous entries: </p>
    </div>

    If your JavaScript is before the HTML elements, they won't exist in the page when your JavaScript loads, so document.getElementById will return null. However, if you wait to set the variables until those elements exist (either because they're listed before the <script> tag, or because the DOM content has loaded), they'll be found.