1

I want to use :nth-child to select the second span using its class

<div id="myDiv">
     <span class="mySpans">Stuff</span>
     <span class="mySpans">Stuff</span>
     <span class="mySpans">Stuff</span>
</div>

I am trying the following with no luck

'div#myId > span:nth-child(2 of span.mySpans)';

I am specifically looking to match the element using the nth occurance a class.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
myol
  • 8,857
  • 19
  • 82
  • 143
  • 2
    Sigh, not again. If they're not going to update the selectors-4 TR they should just take it down until it's ready to republish. :nth-match() hasn't existed for years. – BoltClock Mar 27 '17 at 16:00
  • Oh, I wasn't aware in the slightest – myol Mar 27 '17 at 16:02
  • 1
    Yeah, and I don't blame you. The draft is regularly updated at https://drafts.csswg.org/selectors-4, but the TR hasn't been touched since 2013. That's almost *four years* now. – BoltClock Mar 27 '17 at 16:04
  • Ok I updated the question – myol Mar 27 '17 at 16:12

2 Answers2

2

Currently, only Safari supports the selector-list argument of :nth-child() introduced in selectors-4.

There is no other way to do this in CSS besides adapting the overriding technique from here, but with an additional selector for the 3rd .mySpans onward:

div#myId > span.mySpans, div#myId > span.mySpans ~ span.mySpans ~ span.mySpans {
  /* ... */
}

div#myId > span.mySpans ~ span.mySpans {
  /* Remove from previous rule */
}

If this is in JavaScript or some other API that returns a set of elements as the string-like notation in your question suggests, you can just index off of it since your parent element has an ID and therefore you're only concerned with one set of elements (assuming the parent ID is actually unique, of course):

document.querySelectorAll('div#myId > span.mySpans')[1]

See also: Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

Obviously the much-requested :nth-of-class doesn't exist yet.

But if you are happy to use a javascript translation* of this hypothetical CSS:

#myDiv .mySpans:nth-of-class(2) {
color: red;
}

there are two possible translations:

document.getElementById('myDiv').getElementsByClassName('mySpans')[1].style.color = 'red';

document.querySelectorAll('#myDiv .mySpans')[1].style.color = 'red';

N.B. It's not a real translation, of course - it simply locates the element in the Document Object Model (DOM) and then applies style="color: red;" to that element.

Rounin
  • 27,134
  • 9
  • 83
  • 108