Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove closest empty siblings

Let's say I have the following markup:

<p></p>
<p>not empty</p>
<p>not empty</p>
<p></p>
<div class="wrapper">
    // more content inside
</div>
<p>  </p> <-- whitespace, also removed
<p></p>
<p>not empty</p>

How do I remove the empty <p> tags closest to .wrapper? I want a result like this:

<p></p>
<p>not empty</p>
<p>not empty</p>
<div class="wrapper">
    // more content inside
</div>
<p>not empty</p>

So I don't want to remove all empty siblings, just the empty ones next to .wrapper, even if there are multiple.

like image 727
qwerty Avatar asked Feb 18 '23 15:02

qwerty


2 Answers

You can use .prevUntil/.nextUntil combined with the :not(:empty) selector: http://jsfiddle.net/vEtv8/5/.

$("div.wrapper")
    .​​​​​​​​​​nextUntil(":not(p), :not(:empty)").remove().end()
    .prevUntil(":not(p), :not(:empty)").remove();

:empty doesn't count whitespace elements as being empty, though. You could use a function for that: http://jsfiddle.net/vEtv8/4/.

var stopPredicate = function() {
    var $this = $(this);
    return !$this.is("p") || $.trim($this.text()) !== "";
};

$("div.wrapper")
    .nextUntil(stopPredicate).remove().end()
    .prevUntil(stopPredicate).remove();
like image 196
pimvdb Avatar answered Feb 21 '23 04:02

pimvdb


$('.wrapper').prevAll('p:empty').nextAll('p:empty').remove();
like image 24
Abhilash Avatar answered Feb 21 '23 04:02

Abhilash