0

I'm looking for an nth-of-type descendant selector.

I have a class .class-name present a total of 7 times in my DOM tree.

How do I select the 3rd iteration or 4th iteration of the said class?

(the said class has different elements as parents (with different classes applied to them)

I tried this code and it doesn't work: (because nth-of-type refers to the direct parent and I want it to work for the BODY element, which is an ancestor)

    .class-name:nth-of-type(3) {margin-top: -215px;}
    .class-name:nth-of-type(4) {margin-top: 34px;}
    .class-name:nth-of-type(5) {margin-top: -115px;}
    .class-name:nth-of-type(6) {margin-top: 455px;}
    .class-name:nth-of-type(7) {margin-top: 545px;}

(The whole reason for using the said class was to be able to select the N-th iteration of it throughout the DOM tree, to avoid the hastle of targeting each ancestor using more complicated selector rules)

P.S. This is a more clear example than the issue posted here (Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?). It's related, but not a duplicate.

Johnny
  • 479
  • 1
  • 6
  • 15
  • did you try ? .class-name:nth-child(3) – dev_ramiz_1707 Feb 13 '19 at 11:48
  • nth-child, self explanatory , selects the nth-child of a parent and, therefore, isn't suited to select a descendant. See here for more clarity: https://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/ (yes, I already tried with nth-child) – Johnny Feb 13 '19 at 11:49
  • put here your full example with a snippet. thanks – dev_ramiz_1707 Feb 13 '19 at 11:52
  • This is a combination of two distinct limitations of CSS, addressed in the two questions I've now linked to. The best you can do is a querySelectorAll() with the class name in question then index off the resulting node list, but that requires JavaScript. – BoltClock Feb 13 '19 at 11:53
  • dev_ramiz, the full example was linked in the question description; I need to apply 5 different styles to each of those iterations. ... @BoltClock I already read those questions and mine seemed to address the selection issue conundrum more clearly than the one with the odd/even table example. I would not mark it as duplicate, but you have way more rep than I do, so.. Thank you for the suggestion! – Johnny Feb 13 '19 at 12:00
  • @dev_ramiz_1707 If you're referring to the html, it is too big to post here; There are several parents between the body element and each class iteration (15 ancestors or so). Each class iteration is the only child of its direct parent. – Johnny Feb 13 '19 at 12:05
  • 1
    Hmm, I could post an answer instead, adding my JavaScript suggestion. – BoltClock Feb 13 '19 at 12:13

0 Answers0