Remove nearest empty siblings
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 to remove the <p> tag closest to .wrapper ? I want to get this result:
<p></p> <p>not empty</p> <p>not empty</p> <div class="wrapper"> // more content inside </div> <p>not empty</p> Therefore, I do not want to delete all empty siblings, only empty next to .wrapper , even if there are several.
You can use .prevUntil / .nextUntil in combination 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 does not consider whitespace to be empty. You can use the function for this: 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();