4

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
qwerty
  • 5,166
  • 17
  • 56
  • 77

2 Answers2

7

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();
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • Almost, but it doesn't remove if it contains whitespace: http://jsfiddle.net/pptRP/ – qwerty Nov 01 '12 at 11:16
  • Actually, not quite done yet. This removes all empty sibling tags. I only want to remove

    tags.

    – qwerty Nov 01 '12 at 11:19
  • @qwerty: Oops, you're right. You could add an extra check like http://jsfiddle.net/vEtv8/4/. – pimvdb Nov 01 '12 at 11:20
  • 1
    +1 in part because this demonstrates that the documentation for `.nextUntil()`/`.prevUntil()` is wrong -- it doesn't mention that you can use a function as the selector! – Jon Nov 01 '12 at 11:25
  • @Jon: Funny, indeed it does not state that. In fact, `.parentsUntil` also works with a function. – pimvdb Nov 01 '12 at 11:31
1
$('.wrapper').prevAll('p:empty').nextAll('p:empty').remove();
Abhilash
  • 1,610
  • 9
  • 19