简体   繁体   中英

How to check if content of element is empty and if so, remove that element in jquery

I'm currently trying to select any h2 element inside of a certain div that does not have content in it and remove it. This is my html code:

 <div class="skipToContainer">
     <h2 class="vidSkipTo">Hello </h2>
     <h2 class="vidSkipTo"></h2>
     <h2 class="vidSkipTo"></h2>
     <h2 class="vidSkipTo"></h2>
 </div>

These are a couple jQuery codes I have tried to no avail:

jQuery(".skipToContainer .vidSkipTo").each (function () {
    if (jQuery(this).text().trim() === '')
        jQuery(this).remove();
}

jQuery(".skipToContainer h2").each (function () {
    if (jQuery(this).text().trim() === '')
        jQuery(this).remove();
}

jQuery(".skipToContainer h2").each (function () {
    if (jQuery(this).text() === '')
        jQuery(this).remove();
}

Any suggestions?

Note: I'm doing these tests on a local WordPress site. Not sure if that matters but just to let you know.

Try

 jQuery(".skipToContainer h2").filter(":empty").remove(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="skipToContainer"> <h2 class="vidSkipTo">Hello </h2> <h2 class="vidSkipTo"></h2> <h2 class="vidSkipTo"></h2> <h2 class="vidSkipTo"></h2> </div> 

 $('.skipToContainer > .vidSkipTo:empty').remove(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="skipToContainer"> <h2 class="vidSkipTo">Hello </h2> <h2 class="vidSkipTo"></h2> <h2 class="vidSkipTo"></h2> <h2 class="vidSkipTo"></h2> </div> 

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