Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.


No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

Vanilla JavaScript Count All Words on a Webpage

Sep 1, 20181 min readTutorial, JavaScriptViews:

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;

Copy and paste the JS code into your browser console to test it on any website. Just make sure you target the right selector.
The JavaScript word counter logs out the total number of words to the console

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!

© 2019 - TechStacker
Powered byGatsbyGithubNetlify