简体   繁体   English

如何获得每个标题的最后一个孩子?

[英]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;
        }
    }
}

Demo 演示版

<div class="span8">
<h1>heading</h1>
  <p>foo</p>
  <p>bar</p>
  <p>foo</p>
  <p>bar</p>
</div>    

  .span8 > p:last-child{ color:red }

If you wrap the content with a div , then it is possible using CSS . 如果用div包装内容,则可以使用CSS

div p:last-child  {
  color:red;
}

See demo 观看演示

It is possible with Jquery. 使用Jquery是可能的。 Here is an example 这是一个例子

$(document).ready(function(){
    $('h1').prev('p').addClass('myclass');
})

Learn more about previous and next on this link 在此链接上了解有关上一个和下一个的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM