How to select and delete a div element if it contains no text and contains only elements?

This is my scenario:

<div><br><div>
<div>
    line one.
    <br>
    line two.
</div>
<div><img src="example.jpg"></div>
<div><br></div>
<div><iframe></iframe></div>
<div><br></div>

I need to check if the div contains NO text, as well as the br tag and removes it.


I tried this:

if ($('div').is(':empty')) { 
    $('div').remove();
} 

This did not work, I think, because empty () does not mean "no text."


I also tried this:

$('div').filter(function() {
    return $.trim($(this).text()) === '';
}).remove();

This worked, however, it removed all div tags containing only text, so all my images and any other html tag inside the div were deleted.


The last thing I tried was this, but then I realized that this does not take into account the text that may be in the div.

$('div br:only-child').remove();

I am still new to jquery and apologize for any annoyance that I can cause by asking y'all for help. Thank you in advance!!

+4
source share
3

jQuery :has() , div, br :

$('div:has(br)').filter(function() {
  return !this.textContent.trim();
}).remove();

, :only-child, div br :

$('div:has(br:only-child)').filter(function() {
  return !this.textContent.trim();
}).remove();

br, , , :only-child.

, br.

$('div:has(>br)').filter(function() {
  return !this.textContent.trim() && !$('br', this).siblings(':not(br)').length;
}).remove();

div , , - br. , br, , > .

+4

, <br>,

$('div:has(br)').filter(function(){
   var $div= $(this), $children=$div.children();
   // check if all children are <br>
   if($children.length === $children.filter('br').length){
        // return true or false depending on text
        return !$div.text().trim();
   }
   // children are not all <br>
   return false;
}).remove(); 
+1

I used the search and destroy approach:

https://jsfiddle.net/ay4ax3nz/

$("div").each(function(){
    if($(this).html() === '<br>' || $(this).html() === '<br />'){
        $(this).remove();
    }
});
+1
source

Source: https://habr.com/ru/post/1629413/


All Articles