0

Suppose this 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?

I was trying it like this:

h1 ~ p:last-child /*wouldn't work*/ /* it would select last-child of p*/
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

4 Answers4

1

That is simply not possible with CSS, as there is no way to select elements backward or up the tree (looking forward to 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:

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

(p.last) Or with 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;
        }
    }
}
bjb568
  • 11,089
  • 11
  • 50
  • 71
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 }
Ravi Patel
  • 5,121
  • 2
  • 25
  • 44
0

If you wrap the content with a div, then it is possible using CSS.

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

See demo

newTag
  • 2,149
  • 1
  • 22
  • 31
-1

It is possible with Jquery. Here is an example

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

Learn more about previous and next on this link

Ayaz Shah
  • 435
  • 1
  • 5
  • 24