Example HTML : And jQuery for checking the empty elements : Now I got all empty"/>
  简体   繁体   中英

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

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

Something like :

删除空<p>,但每组只允许一个

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

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> 

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

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;
});

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