1

So, I have a ul element list and I want to select the first 3 li elements after .active class

<ul>
 <li>The #1</li>
 <li>The #2</li>
 <li class="active">The #3</li>
 <li>The #4</li>
 <li>The #5</li>
</ul>

I was thinking something like this:

ul li.active ~ li:nth-child(n+3)

But it does not work. Anyone can help me out with this?

P.S.: Class .active is dynamically changing, so any ul li:nth-child(n+3) will not help.

zagzter
  • 229
  • 1
  • 11

1 Answers1

6

It appears you can not do this using nth options on selectors based on your markup and how the hierarchy works.

If you're looking to give the three li selectors after the li.active selector a red background, you can target them within your css in one call by appending + li as many times as needed, grouping the selectors together, like so:

li.active + li, 
li.active + li + li, 
li.active + li + li + li {
  color: red;
}
<ul>
 <li>The #1</li>
 <li>The #2</li>
 <li class="active">The #3</li>
 <li>The #4</li>
 <li>The #5</li>
</ul>
adprocas
  • 1,863
  • 1
  • 14
  • 31
  • it's not going to help me, sorry :/ – zagzter Mar 12 '18 at 12:49
  • 1
    Can you explain why? You said you wanted the three li's "selected" after the active class li. This achieves that. Can you explain why this won't help? – adprocas Mar 12 '18 at 12:52
  • 2
    @zagzter this is the only way, if you don't like it then you cannot do it – Temani Afif Mar 12 '18 at 12:56
  • @zagzter, people have explained why using `nth` doesn't work with this hierarchy. This really is your best solution. I don't believe there is another way to do this unless you use JavaScript or change your markup. What is wrong with doing it this way? Please give me the reason why this doesn't help you. Withholding information isn't going to help you. – adprocas Mar 12 '18 at 13:11
  • @zagzter did you find a solution? – adprocas Mar 14 '18 at 17:39