5

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. Commented Feb 5, 2016 at 14:41
  • Is there an alternative way to do this then apart from using js? Commented Feb 5, 2016 at 14:41

2 Answers 2

13

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)

Sign up to request clarification or add additional context in comments.

6 Comments

Why do you think it is dirty? It's what + was made for.
that may actually work as its always the 2nd i need after an element with a selected class. thanks, ill give it a shot
@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-: Selectors are sensitive to DOM structure by design. The OP's use case is hinged on the structure anyway.
@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.
|
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 Comments

How about this @BoltClock, can i do the same and select the element before it? Or better, is there a way to do that?
@user1009698: Unfortunately, there is no previous sibling selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.