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.

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

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

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

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


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