Wojtek Wojtek - 4 days ago 6
HTML Question

How to count selected word in HTML body by JavaScript

I would like to count occurency of specific word/pharse in a HTML body. For example in a paragraph. The special thing is that i want to count by matching with a variable - that refers to string, not a string itself.

The code below returns only zeroes.

Maybe it's something with array_values --> like it doesn't see it as an array. I'm a begginer so every hint matters.

var array_values = document.getElementsByClassName('a'); // <p class="a"> A paragraph that contains some text.

var chosenWord = document.getElementById("input").value; // a word that i would like to count (how many times it occours in paragraph)

var count = 0;
for (var i = 0; i < array_values.length; i++) {
if (array_values[i] == chosenWord)
count++;
}

alert("The word " + chosenWord + "occours " + count + "times");

Answer

One minor change and it works! The change is in declaration of first variable - had to add innerHTML - without it we create an [HTML OBJECT] which (I suppose) can't be used for that purpose. Thanks to Antoine who created trim and split and an Array.

var lines = document.getElementById("text").innerHTML.trim().split(" "); // A number of paragraphs that contains some text are nested in some <DIV id="text"> 

var chosenWord = document.getElementById("input").value; // a word that i would like to count (how many times it occours in paragraph)

var texts = [];
    for (var i=0; i < lines.length; i++) {
    //only push this line if it contains a non whitespace character.
      if (/\S/.test(lines[i])) {
          texts.push($.trim(lines[i]));
      }
    }

alert(JSON.stringify(texts)); // the block is creating an array of words from selected DIV. Alert is just to show you an array.


var count = 0;
for (var i = 0; i < texts.length; i++) {
    if texts[i] == chosenWord) 
        count++;
}

alert("The word " + chosenWord + "occours " + count + "times");
Comments