Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first element which is placed after another element but not immediately

How is it possible to select only the first element (e.g. h2) after another element (e.g. h1) but which is not necessarily placed immediately after ?
So, element+element (e.g. h1 + h2) does not work because it selects elements that are placed immediately after elements

<h1> Title1 </h1>
..... <--! many tags but h2 -->
<h2> h2 Title2 selected </h2>
..... <--! many tags but h1 and h2-->
<h2> h2 Title3 not selected </h2>
like image 603
Stef1611 Avatar asked Oct 20 '25 08:10

Stef1611


1 Answers

Now it's possible with one selector:

h1:first-of-type ~ h2:not(h1:first-of-type ~ h2 ~ h2) {
  color:red;
}
<div>
  <h2>h2 Title3 not selected </h2>
  <h1> Title1 </h1>
  <p>text</p>
  <h2> h2 Title2 selected </h2>
  <h3>text</h3>
  <h2> h2 Title3 not selected </h2>
</div>

Old Answer

I don't think you can achieve this with one selector, so you can try something like below:

h1:first-of-type ~ h2 {
  color:red;
}
h1:first-of-type ~ h2 ~ h2 {
  color:initial; /*we reset the style for the others*/
}
<div>
  <h2>h2 Title3 not selected </h2>
  <h1> Title1 </h1>
  <p>text</p>
  <h2> h2 Title2 selected </h2>
  <h3>text</h3>
  <h2> h2 Title3 not selected </h2>
</div>
like image 184
Temani Afif Avatar answered Oct 21 '25 21:10

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!