Trouble getting real time word count from html textbox

I am very new to html and javascript. I have a textbox and am trying to count the number of words, then displaying the count in real time. I do not understand what I am doing wrong in this, or how to correct it. textContent does not make much sense to me.

<html>
  <head>
    <style>
      input[type='text'] {width:50px;}
      textarea {width:500px;height:300px;}
    </style>
  </head>
  <body>
  <div>
    <h2>Test</h2>
    <p>The number of words is <span id="wordCount"></span></p>
    <textarea id="toCount"></textarea>
  </div>
      <script>

    document.getElementById('toCount').addEventListener('input', function () {
        var text = this.textContent,

        count = text.trim().replace(/\s+/g, ' ').split(' ').length;

        document.querySelector('.wordCount').textContent = count;

    });
    </script>
  </body>
</html>

The error that I get right now says
Uncaught TypeError: Cannot set property 'textContent' of null

75 thoughts on “Trouble getting real time word count from html textbox”

Leave a Comment