Select the first 3 sibling elements (<p>) of another element (<h2>)

Welcome to ScriptMode
Sankar
Posts: 54
Joined: Thu Dec 10, 2015 11:55 am

Select the first 3 sibling elements (<p>) of another element (<h2>)

Postby Sankar » Wed Feb 24, 2016 5:40 am

How do I select all the <p> tags that are siblings to the first 3 <h2> tags using CSS?

The tags with the text "one", "two", "three" should be red but the text "four", and "five" should not be selected.

Here is my example code but I am not sure what that CSS selector should look like.

.container h2 + p {
color: red
}
<div class="container">
<h2>Some text</h2>
<p>One</p>
<h2>Some text</h2>
<p>Two</p>
<p>Two</p>
<h2>Some text</h2>
<p>Three</p>
<p>Three</p>
<p>Three</p>
<h2>Some text</h2>
<p>Four</p>
<p>Four</p>
<p>Four</p>
<p>Four</p>
<h2>Some text</h2>
<p>Five</p>
<p>Five</p>
<p>Five</p>
<p>Five</p>
<p>Five</p>
</div>

Heisenberg
Posts: 117
Joined: Thu Aug 27, 2015 7:16 am

Re: Select the first 3 sibling elements (<p>) of another element (<h2>)

Postby Heisenberg » Thu Mar 03, 2016 1:28 pm

If overriding is not out of the question, then it becomes much, much easier — you can simply override it with a different selector instead:

.container h2 ~ p {
color: red
}

.container h2:nth-of-type(4) ~ p {
color: currentColor
}
<div class="container">
<h2>Some text</h2>
<p>One</p>
<h2>Some text</h2>
<p>Two</p>
<p>Two</p>
<h2>Some text</h2>
<p>Three</p>
<p>Three</p>
<p>Three</p>
<h2>Some text</h2>
<p>Four</p>
<p>Four</p>
<p>Four</p>
<p>Four</p>
<h2>Some text</h2>
<p>Five</p>
<p>Five</p>
<p>Five</p>
<p>Five</p>
<p>Five</p>
</div>


Return to “General”

Who is online

Users browsing this forum: No registered users and 2 guests