Tanveer Shaikh
Tanveer Shaikh

Reputation: 1688

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.

Upvotes: 0

Views: 1459

Answers (5)

Nishit Maheta
Nishit Maheta

Reputation: 6031

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);
});

Upvotes: 5

Pradeep
Pradeep

Reputation: 74

Try this..

alert($("#master_DefaultContent_rts_ts1891_tab_2901 div:contains('No Records Found')").length);
<div id="master_DefaultContent_rts_ts1891_tab_2901">
	<div>No Records Found</div>
	<div>No Records Found</div>
</div>

Upvotes: 0

Giuseppe
Giuseppe

Reputation: 288

I would use the contains jQuery filter as Pensan mentioned above - this seems like the simplest way. The following would give you the number that you're after:

$('#parentDiv').find(":contains('No Records Found')").length

Or if you prefer

$("#parentDiv div:contains('No Records Found')").length

Upvotes: 1

pensan
pensan

Reputation: 420

Or you could use the jQuery "Contains" filter:

jQuery(":contains('No Records Found')")

Upvotes: 2

Khalid
Khalid

Reputation: 4808

This code may help you, I didn't test but if it doesn't work it can give you an idea :

var count = $("#master_DefaultContent_rts_ts1891_tab_2901").text().split('No Records Found').length - 1

Upvotes: 1

Related Questions