Sanjeev K Sanjeev K - 11 days ago 6
HTML Question

Remove div if it has BR and no text jQuery

I have a page where some

div
has content and some are having only
BR
tag, I am trying to remove the
div
that div has only BR tag, following is the html format

Some are like this

<div>
<br>
</div>


And Some are like this

<div>
<br>
Text goes here text goes here..Text goes here text goes here.. Text goes here text goes here..
</div>


As I know I can find the blank div and remove it easily but hard to check the inner
BR
tag and remove, can somebody please help!

I tried to check blank div like this

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

Answer

:empty selector will not work as the div has br element.

You can use .filter() to get all div element which has no text() then remove() can be used.

$('div').filter(function() {
  return $(this).text().trim().length == 0;
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <br>Text goes here text goes here..Text goes here text goes here.. Text goes here text goes here..
</div>
<div>
  <br>
</div>

Comments