2

I there a way of selecting (using css) the nth child from an element with a certain class. For example, for the following, how could I select the li element with the id="this" (shown for explanation purposes)? So basically I want to say the 2nd element from the element with class="selected"

<ul>
    <li></li>
    <li class="selected"></li>
    <li></li>
    <li id="this"></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
2
  • 1
    No, the nth-child doesn't work that way. It numbers the children based on their index below the parent. You can ofcourse write .selected + li + li for the 2nd element from that one but if its say the 8th child it becomes too much.
    – Harry
    Feb 5, 2016 at 14:41
  • Is there an alternative way to do this then apart from using js? Feb 5, 2016 at 14:41
7

Actually you could do with + selector. It is a bit dirty, but works in your case. All you need is to know the exact position of element you need.

.selected + li + li (adding + li as much times as you need)

6
  • 1
    Why do you think it is dirty? It's what + was made for.
    – BoltClock
    Feb 5, 2016 at 14:43
  • that may actually work as its always the 2nd i need after an element with a selected class. thanks, ill give it a shot Feb 5, 2016 at 14:44
  • @BoltClock because if position is not second its way too much code, and it is very sensitive for DOM changes. I'll rather think how to do it more clearly and better customizable
    – WinK-
    Feb 5, 2016 at 14:45
  • 1
    @WinK-: Selectors are sensitive to DOM structure by design. The OP's use case is hinged on the structure anyway.
    – BoltClock
    Feb 5, 2016 at 14:47
  • @BoltClock nobody is denying that selectors are sensitive to DOM structure. But the point is that if one is interested in doing +table+div+table+div+table+div+div like 7 elements or +li+li+li+li+li. Then it'd be cleaner to do +:nth-sibling(8) or +li:nth-sibling(5) but no such facility exists.
    – barlop
    Nov 4, 2017 at 21:00
4

You use combinators to select an element relative to another element (which I'll refer to here as the reference element).

In this case, as you want the second sibling after li.selected, you need to step forward by two elements, using two + sibling combinators:

li.selected + li + li

As mentioned, you will need to repeat + li n times to reach the nth following sibling of your reference element (see also this related answer). There is no nth-sibling combinator, and :nth-child() is not designed to work with relative selectors.

2
  • How about this @BoltClock, can i do the same and select the element before it? Or better, is there a way to do that? Feb 5, 2016 at 15:31
  • @user1009698: Unfortunately, there is no previous sibling selector.
    – BoltClock
    Feb 5, 2016 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.