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.
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();
$('.wrapper').prevAll('p:empty').nextAll('p:empty').remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With