Count Words Length Of Any HTML DOM Element - JavaScript

Hello, Friends back with another easy trick that can help you to count how many words in any HTML Element with Native a JavaScript Method.

A Cover pic of a web page showing text


In this Trick, we are going to use javascript Native innerText property to access the text content of from HTML DOM Element.

We have a few more options like textContent or nodeValue but these properties when used they gonna fetch all the text even inside the script and style tags and also the unnecessary whitespace so we don't want this words to get counted as this content gonna hide from users so no use of counting these.

How To Count Words?:

The easiest way to count words is when the characters are separated by spaces means when a sequence of characters are separated by space then we assume that it becomes one word and after space next sequence characters until next space. 

We identify words in an element from the spaces that separated them from each other so we break each word after space and add it to an array that array will be used to count the words. 

We used the length property of that array to get the length and this length will be the total words in that element and webmasters and blogger can use this in their plugins or widgets. 

The Code:

function ABT_CountWords(Element){
    let arrayOfWords = document.querySelector(`${Element}`).innerText.split(" ");
    return arrayOfWords.length;


The red highlighted text is where you need to add your element id or class name to get the length of the word from it.
To invoke the above function you need to call it wherever you want the words to count to get displayed.

Hope this easy tricky post may have helped you in learning something new. If you liked it don't forget to share.

No comments:

Post a Comment