2014-03-19 138 views
0

假设这个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---> 

,并选择此只用CSS是不可能的?

我试图像这样:

h1 ~ p:last-child /*wouldn't work*/ /* it would select last-child of p*/ 
+0

H1 p:上一个孩子{....} – ShibinRagh

+0

@ShibinRagh将无法正常工作。这是无效的。 h1还没有小孩 –

+0

非常感谢,我明白了 – ShibinRagh

回答

1

这是完全不可能的CSS,因为没有方法来选择要素向后或上树(期待CSS4 ...)。你将不得不使用其中的一个:

<section> 
    <h1>heading</h1> 
    <p>foo</p> 
    <p>bar</p><!---this should be selected---> 
</section> 

section p:last-child)或者:

<h1>heading</h1> 
<p>foo</p> 
<p class="last">bar</p><!---this should be selected---> 

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; 
     } 
    } 
} 
+0

我没有看到的前面或后面的兄弟姐妹,但只喜欢-的类型搜索的CSS的东西。 ... –

+0

固定。请参阅编辑。 – bjb568

-1

这是可能使用jQuery。下面是一个example

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

了解更多关于前面和后面的这个link

+0

不会得到最后一个。 – bjb568

0

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 } 
0

如果您有div包裹的内容,那么就可以使用CSS

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

See demo

相关问题