2

Is there a way to select the first element with a some class after n elements? For example in the following HTML, I want to be able to select only the first div that has CSS class apple after the 5th div, resulting in the 7th div element being selected.

<div>
    <div class="data-class">1</div>
    <div class="data-class">2</div>
    <div class="data-class">3</div>
    <div class="data-class apple">4</div>
    <div class="data-class">5</div>
    <div class="data-class">6</div>
    <div class="data-class apple">7</div>
    <div class="data-class apple">8</div>
    <div class="data-class">9</div>
    <div class="data-class apple">10</div>
</div>

This selector selects all the divs, but I only want the first: .data-class.apple:nth-child(n+5)

And this one doesn't even work: .data-class.apple:nth-child(n+5):first-child

I have put the HTML and CSS samples here.

UPDATE
Current CSS selectors

.data-class{
  background-color: #0ea;
  padding: 10px;
  margin-bottom: 5px;
  border: 1px solid #444;
}

.data-class:nth-child(n+5)+.apple{
  background-color: #f0f;
}
Nick Stauner
  • 395
  • 3
  • 13
tusharmath
  • 10,622
  • 12
  • 56
  • 83

3 Answers3

3

To select an element appearing after some other element, use the ~ combinator:

.data-class:nth-child(5) ~ .data-class.apple {
  background-color: #f0f;
}

You won't be able to match only the first .apple that occurs using just one selector. You will need to create another rule to undo the styles that you apply for subsequent .apple elements:

.data-class:nth-child(5) ~ .data-class.apple ~ .data-class.apple {
  background-color: #0ea;
}

This technique is explained here.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Can you please update the jsbin link ? I can't get it to work :( – tusharmath May 17 '14 at 07:37
  • Sorry, I don't quite know how to modify/fork bins. If you show the CSS you want to change I can update my answer accordingly. – BoltClock May 17 '14 at 09:49
  • I have added the css classes with the selectors also. Would the same thing be possible via a CSS4 selector? – tusharmath May 18 '14 at 06:52
  • I edited my answer. I'm not sure if it would be possible, `:nth-match()` allows combinators in the complete profile but not the CSS profile, which can be problematic. – BoltClock May 18 '14 at 07:04
0

it is better to say having css class, not having css. I couldn't find the appropiate selector strictly. Instead of this, you could use jquery and write javascript function which use for loop from 5th child until it finds class containing apple. You may use jquery n-th-child to select child in loop and hasClass to determine if it contains apple. Therefore select result by passing result to n-th-child function.

changtung
  • 1,614
  • 15
  • 19
0

It uses this test:

div > .data-class.apple, .data-class{.....}

or another use:

div > .apple:not(.data-class){.....}
Nick Stauner
  • 395
  • 3
  • 13
Kisspa
  • 584
  • 4
  • 11