Kyrtap
Kyrtap

Reputation: 158

How to count specified word occurrence in multiple elements

I have some amount of elements with class of "shoutbox_text", how canI count specified word occurrence in all of them? (Inner HTML of them is just plain text, there isn't anymore tags inside.)

Upvotes: 0

Views: 67

Answers (1)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

Assuming you want to search the word "word", you'd do:

var elems = document.getElementsByClassName('shoutbox_text'),
    n = 0;
for(var i=0; i<elems.length; i++){
  var text = elems[i].innerHTML;
  n += (text.match(/word/gi) || []).length;   
}
alert(n);

If you have the word in a variable word, and the search is case sensitive you could do:

var elems = document.getElementsByClassName('shoutbox_text'),
    n = 0;
for(var i=0; i<elems.length; i++){
  var text = elems[i].innerHTML;
  n += text.split(word).length - 1;   
}
alert(n);

Cheers, from La Paz, Bolivia

Upvotes: 1

Related Questions