0

Consider this HTML:

<p>Foo</p>
<p>
  <br>
</p>
<p>Bar</p> <!-- I want to select this p element -->
<p>Baz</p>

Is there any way in CSS to select "the p element after a p element containing a br element"?

I know I can fall back to using JavaScript for this, but I was curious to see if there was some funky combination of sibling selectors, or some magical pseudoclass I'm yet to come across.

Alec
  • 1,126
  • 1
  • 10
  • 23
  • NB: Sure a parent selector could work, but not exactly what I'm asking here. Parent selectors are slightly against the grain of CSS, which only ever acts in a single direction down the DOM. In my case, the element I want to act on is still after all the other things I need to know about, so there would be no need to go back up the DOM or perform a second pass, etc. – Alec Oct 24 '18 at 11:30
  • it is still called a *parent selector* ... you want to look what is inside your element, so you need to first go down then go up again, which is actually not possible with CSS (read the duplicate and you will find that you need the `:has()` selector) ... basically you want this : start from `br`, check if the parent is `p`, if yes selector it then select the `p` after it .. which is the same as : select the `p` that contains the `br` then select the p after it – Temani Afif Oct 24 '18 at 11:34
  • Yeah. I guess I was more fishing for if I'd missed something like `:blank` that would have solved this, but I guess it's back to JS then. – Alec Oct 24 '18 at 11:38
  • 1
    In case you're interested, [here's a deep dive into how parent selectors play into this and the unidirectionality of Selectors](https://stackoverflow.com/questions/28708741/how-do-i-select-an-element-based-on-the-state-of-another-element-in-the-page-wit/28793064#28793064) despite what it might seem. – BoltClock Oct 24 '18 at 12:27

1 Answers1

-2

In this given code

`

Foo


Bar

Baz

`

If you want to select the 3rd p then you can use a Pseudo Class :nth-child()

So the answer would be p:nth-child(3)

If these p tags are inside a container than use that as combinator for the desired result otherwise it would select all the 3rd p tags in the html document

Temani Afif
  • 180,975
  • 14
  • 166
  • 216