4

假设我有以下标记:

<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>

如何删除<p>最接近的空标签.wrapper?我想要这样的结果:

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

所以我不想删除所有空的兄弟姐妹,只是旁边的空兄弟姐妹,.wrapper即使有多个。

4

2 回答 2

7

您可以将.prevUntil/.nextUntil:not(:empty)选择器结合使用:http: //jsfiddle.net/vEtv8/5/

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

:empty但是,不会将空白元素视为空的。您可以为此使用一个函数: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();
于 2012-11-01T11:14:03.253 回答
1
$('.wrapper').prevAll('p:empty').nextAll('p:empty').remove();
于 2012-11-01T11:23:37.130 回答