Remove empty <p>, but allow only one per group

108 views Asked by At

I was wondering how to remove empty elements, but allow only one empty element per group (next to non-empty one) ?

Something like :

Remove empty <p>, but allow only one per group

Example HTML :

<p>Hello world</p>
<p><br></p>
<p><br></p> <!--This will remove-->
<p><br></p> <!--This will remove-->
<p>Lorem ipsum dolor sit amet</p>
<p><br></p>
<p><br></p> <!--This will remove-->
<p>Eum ne nostro admodum</p>
<p><br></p>

And jQuery for checking the empty elements :

var p_empty = $('p').filter(function(i,v){return $.trim($(v).text()).length===0;});

Now I got all empty elements, But any idea how to remove those next empty elements ?

Workflow : http://jsfiddle.net/jmy0uzw1/

PS: I am looking for good JS performance also

3

There are 3 answers

5
AmmarCSE On BEST ANSWER

In your case since you are not using containers, you will have to use sibling selectors + and make sure the preceding p element itself is not of .empty

$('p.empty:not(p:not(.empty) + p.empty)').remove();

var p_empty = $('p').filter(function(i, v) {
  return $.trim($(v).text()).length === 0;
});

p_empty.addClass('empty');

$('p.empty:not(p:not(.empty) + p.empty)').remove();
p {
  padding: 3px 10px;
  background: #eee;
  color: #999;
  font-size: 12px;
  line-height: 12px;
}
p.empty {
  border: 1px dashed #fff;
  background: #edd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p>Hello world</p>
<p>
  <br>
</p>
<p>
  <br>
</p>
<p>
  <br>
</p>
<p>Lorem ipsum dolor sit amet</p>
<p>
  <br>
</p>
<p>
  <br>
</p>
<p>Eum ne nostro admodum</p>
<p>
  <br>
</p>

0
TwilightSun On

Just add more to your filter

var p_empty = $('p').filter(function(i,v){
    return $.trim($(v).text()).length===0 && $.trim($(v).prev().text()).length===0;
});
1
Balachandran On

var p_empty = $('p').filter(function(i, v) {
  return $.trim($(v).text()).length === 0;
});

p_empty.addClass('empty');
$('p.empty + p.empty').remove();
p {
  padding: 3px 10px;
  background: #eee;
  color: #999;
  font-size: 12px;
  line-height: 12px;
}
p.empty {
  border: 1px dashed #fff;
  background: #edd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello world</p>
<p>
  <br>
</p>
<p>
  <br>
</p>
<p>
  <br>
</p>
<p>Lorem ipsum dolor sit amet</p>
<p>
  <br>
</p>
<p>
  <br>
</p>
<p>Eum ne nostro admodum</p>
<p>
  <br>
</p>

Try this:

$('p.empty + p.empty').remove();

Full code

var p_empty = $('p').filter(function(i, v) {
  return $.trim($(v).text()).length === 0;
});

p_empty.addClass('empty');
$('p.empty + p.empty').remove();