Somnath Kharat
Somnath Kharat

Reputation: 3610

Find div inside div with text

I have not paste all the div content here as it is too long

<div id="calendar_month">
    <div>
        <div></div>
        <div>DEMO</div>
    </div>
</div>

I have tried this

 $("#calendar_month").children().each(function () {
     if ($(this).text() == "DEMO") {
         $(this).text("");
     }
 });

Upvotes: 3

Views: 445

Answers (2)

Alex Char
Alex Char

Reputation: 33228

You can use :contains()

$( "#calendar_month div:contains('DEMO')" )

Or after you edit your OP:

$( "#Calendar > div > div:contains('DEMO')" ).text("");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="Calendar">
    <div>
        <div>test</div>
        <div>DEMO</div>
    </div>
</div>

Or after @BhushanKawadkar comment you can use .filter():

$( "#Calendar > div > div" )
  .filter(function( index ) {
    return $(this).text() == "DEMO";
  }).text("");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Calendar">
    <div>
        <div>test</div>
        <div>DEMO</div>
    </div>
</div>

Upvotes: 8

laaposto
laaposto

Reputation: 12213

Your div that contains text DEMO is not a direct children of div with id calendar_month. In your HTML children() will return the first div only.

Use find()

Try:

$("#calendar_month").find('div').each(function () {
     if ($(this).text() == "DEMO") {
         $(this).text("");
     }
 });

DEMO

Or another way(not recommended but just posting for the logic) to this particular markup is to use

$("#calendar_month").children().children().each(function () {
     if ($(this).text() == "DEMO") {
         $(this).text("");
     }
 });

Upvotes: 1

Related Questions