Home > OS >  Select all html elements of a particular type that come after a specific element
Select all html elements of a particular type that come after a specific element

Time:11-05

I would like to select all p elements that come after h1 and by 'after' I mean they are lower on the DOM. They can be either on the same level as h1 or they can be nested multiple times, which means the ~ or selector will not work in this case...

In the example below I want to apply a red background to 'Paragraph 3', 'Paragraph 4' and 'Paragraph 5'.

I am interested in either pure 'css' selector or Nokogiri solution. Thank you.

<!DOCTYPE html>
<html>
<head>

<style> 
  h1 ~ p {
    background: red;
  }

</style>
</head>
<body>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <h1>Foo</h1>
  <p>Paragraph 3</p>
  <div>
    <p>Paragraph 4</p>
  </div>
  <span>
    <div>
      <p>Paragraph 5</p>
    <div>
  </span>
</body>
</html>

CodePudding user response:

Select all the p descendants of all the next elements

h1 ~ p,
h1 ~ * p {
  background: red;
}
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<h1>Foo</h1>
<p>Paragraph 3</p>
<div>
  <p>Paragraph 4</p>
</div>
<span>
    <div>
      <p>Paragraph 5</p>
    <div>
  </div>

  • Related