简体   繁体   中英

How to select and remove a div element if it doesn't contain text and only has <br> 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 a div contains NO text and has a br tag then remove it.


I tried this:

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

This didn't work I think because empty() doesn't mean "no text."


I also tried this:

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

This worked, however it removed all div tags that contained anything but text, so all my images and any other html tag inside of a div were removed.


The last thing I tried was this but then realized this didn't account for the text that may be in the div.

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

I'm still new to jquery and apologize for any annoyance I may cause asking for help from y'all. Thanks in advance!!

You could use the jQuery :has() selector in order to select div elements that have a br descendant element:

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

As you mentioned in your question, you could also combine that with the :only-child selector if you only want to remove the div element if the br element is the only child:

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

If there can be multiple br elements, then you obviously shouldn't be using :only-child .

The better approach would be to check the length of sibling elements that are not br elements.

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

In the query above, the div element will be removed if it doesn't contain any text and it only has descendant br elements. As addressed in the comments, if you only want to check for br elements that are direct descendants, use the child combinator, > , in the initial selector as well.

Check the children of the element are only <br> then check for empty text

$('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(); 

I used a find and destroy approach:

https://jsfiddle.net/ay4ax3nz/

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

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