How can I target a specific group of siblings in a

2019-01-12 10:14发布

问题:

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.

回答1:

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.