查找特定结束标记旁边的HTML元素

时间:2016-11-01 17:56:44

标签: javascript jquery dom

我正在查看父<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>

4 个答案:

答案 0 :(得分:3)

您可以根据HR元素是否是同一父元素的最后一个子元素来过滤HR元素

$('hr').filter(function() {
    return this === this.parentNode.lastElementChild;
}).remove();

FIDDLE

或定位任何也是最后一个孩子的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片段仍然被破坏:

Working example

答案 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();

示例:https://jsfiddle.net/zmb79f3a/1/

答案 3 :(得分:0)

jQuqery解决方案归结为使选择器正确:

if( $( 'main .container:last-child' ).length > 0 ){
  // do your stuff 
}