Learn how to count all words on a specific part of a website with Vanilla JavaScript.
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(".posts-content"))
function wordCount(words) {
var count = 0
for (var i = 0; i < words.length; i++) {
count += words[i].textContent.split(" ").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.