简体   繁体   中英

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

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> 

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

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