我正在查看父<hr>
}中的最后一个<main>
标记是否存在于结束</main>
标记之前。
因此,在下文中,<hr>
标记中最后一个<main>
标记位于结束</main>
标记之前,是目标标记:
<main>
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem
</div>
<hr class="container" />
</main>
如果例如前面有<hr>
标记,则不应删除<div>
:
<main>
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem
</div>
</main>
答案 0 :(得分:3)
您可以根据HR元素是否是同一父元素的最后一个子元素来过滤HR元素
$('hr').filter(function() {
return this === this.parentNode.lastElementChild;
}).remove();
或定位任何也是最后一个孩子的HR元素
$('main hr:last-child').remove();
答案 1 :(得分:2)
要实现此目的,您可以获取main
中的最后一个元素,检查它是否为hr
,如果是,则将其删除:
var $last = $('main :last');
if ($last.is('hr'))
$last.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem ipsum
</div>
<hr class="container" />
<div>
lorem ipsum lorem ipsumlorem ipsumlorem ipsumlorem ipsum
lorem ipsumlorem ipsumlorem
</div>
<hr class="container" />
</main>
这是一个有效的jsFiddle,因为SO片段仍然被破坏:
答案 2 :(得分:1)
if(!$('main hr:last').next().length) // checks if there is a next html element (sibling ) after the last hr tag.
$('main hr:last').remove();
答案 3 :(得分:0)
jQuqery解决方案归结为使选择器正确:
if( $( 'main .container:last-child' ).length > 0 ){
// do your stuff
}