简体   繁体   中英

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM