Tanveer Shaikh Tanveer Shaikh - 7 months ago 12
Javascript Question

Count the number of times a string occurs in a parent div in javascript or jquery

I have a parent div named "master_ts1891_tab_2901" with many child divs under it. I need a function that would return the number of times the string "No Records Found" occurs in the entire parent div.

This string may be under any child div. Note that the string "No Records Found" is a simple text.

Since the entire code is huge, I have addded the sample markup.

Here a code sample:

<div id="master_DefaultContent_rts_ts1891_tab_2901">
<div id="master_DefaultContent_rts_ts1891_s5928" class="section ViewEditSection hidden" layoutid="5928">
<div id="master_DefaultContent_rts_ts1891_s5928_up">
...
...many more divs and tables
...
<td colspan="8" style="text-align:left;"><div>No Records Found</div></td>

...many more divs and tables
...
<td colspan="8" style="text-align:left;"><div>No Records Found</div></td>
<div>




jquery or javascript both will do.

Please help me out.

Answer

Use below code using jQuery/Javascript.

DEMO

$(document).ready(function(){
  var childText = $('#master_DefaultContent_rts_ts1891_tab_2901').text();
  var count = (childText.match(/No Records Found/g) || []).length;
  alert(count);
});