如何删除紧跟在<hr />之后的<hr />?

时间:2017-01-30 15:35:32

标签: javascript jquery html css

我有HTML标记,我无法改变。

示例

<p>
  TEXT 1
  <hr>some text
  <hr>
  <hr>TEXT 2
  <hr>some text
</p>

我想删除紧跟在另一个hr之后没有文字的任何hr。正如您从下面的代码段中看到的那样,额外的hr会导致双线。

我不认为这可以通过CSS实现。我尝试使用相邻(+)选择器,但意识到它显然不会工作。

我查看了使用jQuery :empty,但由于hr是自我关闭的,我发现很难定位。

我很感激任何建议。

&#13;
&#13;
body {
  width: 500px;
  margin: 0 auto;
}
hr {
  border-top: 3px solid #CCC;
  border-bottom: none;
  color: #CCC
}
hr + hr {
  /* display: none; // doesn't work */
}
&#13;
<p>
  TEXT 1
  <hr>some text
  <hr>some more text
  <hr>even more text
  <hr>
  <hr>TEXT 2
  <hr>some text
  <hr>some more text
  <hr>even more text
</p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:5)

您可以使用span元素以编程方式包装文本节点,然后使用您建议的初始选择器hr隐藏同级hr + hr元素。在这样做时,将考虑文本节点,因为它们现在是span个元素,并且相邻的hr元素将被隐藏。

作为旁注,HTML无效,因为hr元素不能嵌套在p元素中。为了这个例子,我将p元素替换为div,但它仍然适用于p元素,并且技术上不需要更改HTML。 / p>

$('.parent-element').contents().filter(function() {
  return this.nodeType === 3 && this.textContent.trim() !== '';
}).wrap('<span/>');
hr {
  border-top: 3px solid #CCC;
  border-bottom: none;
  color: #CCC
}
hr + hr {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent-element">
  TEXT 1
  <hr>some text
  <hr>some more text
  <hr>even more text
  <hr>
  <hr>TEXT 2
  <hr>some text
  <hr>some more text
  <hr>even more text
</div>

答案 1 :(得分:2)

您可以使用:nth-child()选择器。因此,在您的情况下,您可能希望使用:nth-child(even)

body {
  width: 500px;
  margin: 0 auto;
}
hr {
  border-top: 3px solid #CCC;
  border-bottom: none;
  color: #CCC
}
hr:nth-child(even) {
  display: none;
}
<p>
  TEXT 1
  <hr>some text
  <hr>some more text
  <hr>even more text
  <hr>
  <hr>TEXT 2
  <hr>some text
  <hr>some more text
  <hr>even more text
</p>