Chris
Chris

Reputation: 2652

How can I target a specific group of siblings in a flat hierarchy?

Assume you have this HTML:

<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

Note that the hierarchy is flat.

Now try to select the "middle pair" of <p> elements. Is this possible? I really can't figure out how.

This selector only grabs the first <p> following the <h1>:

h1:nth-of-type(2) + p

But this selector grabs the correct pair of <p> elements plus all the following <p> elements that appear after the pair we want:

h1:nth-of-type(2) ~ p

Is it possible?

No JavaScript. No markup changing. Generic solution. Any number of <h1>s or <p>s are allowed, and the number two, in this case, is arbitrary.

I'm thinking maybe this is possible using some using the :not() selector, but I can't seem to figure it out. Kind of like selecting the "general siblings" and then excluding as necessary, or something similar.

Upvotes: 6

Views: 428

Answers (1)

BoltClock
BoltClock

Reputation: 724472

Due to the way the general sibling combinator works, it is not possible to limit a selection of siblings to a specific range or group, even of consecutive siblings. Even the :not() selector won't be of any help here.

You will have to use JavaScript to target the right elements. jQuery's .nextUntil() method immediately springs to mind.

Upvotes: 5

Related Questions