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

Suppose 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 selecting the "middle pair" of <p> elements. Is it possible? I really can’t understand how.

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

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

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

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

Is it possible?

No javascript. Changing the layout does not change. Common decision. Any number <h1> or <p> valid, and the number 2 in this case is arbitrary.

I think it's possible, it's possible using some of them using the :not() selector, but I can't figure it out. Like choosing β€œcommon brothers and sisters,” and then eliminating, if necessary, or something like that.

+4
source share
1 answer

Due to how the general combined combinator works, it is not possible to limit the choice of siblings to a specific range or group, even consecutive siblings. Even the :not() selector will not help here.

You will need to use JavaScript to configure the correct elements. The jQuery .nextUntil() method immediately comes to mind.

+3
source

Source: https://habr.com/ru/post/1445318/


All Articles