[英]How to get last-child of each heading?
Suppose this HTML: 假设此HTML:
<h1>heading</h1>
<p>foo</p>
<p>bar</p><!---this should be selected--->
<h1>heading</h1>
<p>foo</p>
<p>bar</p>
<p>foo</p>
<p>bar</p><!---this should be selected--->
And to select this only with CSS is not possible? 并不能仅通过CSS选择此选项?
I was trying it like this: 我正在这样尝试:
h1 ~ p:last-child /*wouldn't work*/ /* it would select last-child of p*/
That is simply not possible with CSS, as there is no way to select elements backward or up the tree (looking forward to CSS4…). CSS根本无法做到这一点,因为无法选择向后或向上选择树的元素(期待CSS4…)。 You will have to use one of these: 您将必须使用以下之一:
<section>
<h1>heading</h1>
<p>foo</p>
<p>bar</p><!---this should be selected--->
</section>
( section p:last-child
) Or: ( section p:last-child
)或:
<h1>heading</h1>
<p>foo</p>
<p class="last">bar</p><!---this should be selected--->
( p.last
) Or with JS: ( p.last
)或使用JS:
var e = document.getElementsByTagName('h1');
for (var i = 0; i < e.length; i++) {
var f = e[i].nextSibling;
while (f && f.tagName == 'P') {
var n = f.nextSibling();
if (!n) {
f.classList.add('last');
} else {
f = n;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.