Vanilla JavaScript: Count All Words on a Webpage

Sometimes it’s useful to count all the words on a post or page. Are you building a Word Counter feature for your website? You can use the following JavaScript code snippet to do exactly that — and fast.

var wordsInPost = wordCount(document.querySelectorAll(".post-content"));

function wordCount(words) {
    var count = 0;
    for (var i = 0; i < words.length; i++) {
        count += words[i].textContent.split(/\s/).length;
    }
    return count;
}

console.log(wordsInPost);
Copy and paste the JS code into your browser console to test it on any website. Just make sure you target the right selector.

What the JavaScript function does

  • It counts all the words within your target element. In the example above, we target a .post-content class selector.
  • The word count includes all text elements (headings, paragraphs, lists, blockquotes etc.). Everything relevant.
  • It excludes whitespace, commas etc.

How to use the JavaScript function

  • Replace the .post-content class with whatever class, id, or element selector you have for your posts or pages.

Note: you can use getElementsByClassName() instead of querySelectorAll().

You test can with the code in your favorite browser’s console, or on this CodePen.


Has this been helpful?
Let me know in the comments!

Two questions:

  1. I’m using the code you just saw to build a Word Counter component for TechStacker’s content. Is anyone interested in a tutorial on how to do that?
  2. I’m experimenting with ”Code Quickies” on TechStacker. I’m curious how many of you are actually just looking for working code snippets, as opposed to in-depth tutorials (which I also do)?

I reply to everyone! :-)

Comments

No comments to display.