-1

I'm running into an issue using nth-of-type. I have a codepen demonstrating the problem.

https://codepen.io/nicole-staline/pen/bJMMjd

I would assume since the .input_range.marker is the first of it type, the following should work:

.marker {
      &:nth-of-type(1) {
      background:red;
}

But it doesn't, I have to use nth-of-type(4) to target it. Which doesn't make any sense to me.

I can reasonably assume that it's counting the other range inputs, but it shouldn't, unless I'm misunderstanding how nth-of-type works.

Hate to repost, but last question was immediately closed as a duplicate and linked me to an article that didn't address my question.

Nicole Staline
  • 557
  • 4
  • 15

2 Answers2

1

:nth-of-type() selects elements by type, not by class. So even when you use it on a class it will ultimately resolve to the type and its siblings, which in this case is an input.

codeth
  • 557
  • 3
  • 7
1

This is expected behaviour, the nth-of-type considers all siblings under the parent it was called upon, which means as per your code, all input's under input_range are considered.

If you want a CSS solution, you might have to resort to making a wrapper div and scope your classes to that:

<div class="input_range">
    <input class="range" type="text" value="1"/>
    <input class="range" type="text" value="2"/>
    <input class="range" type="text" value="3"/>

  <div class="subset">
    <input class="marker" type="text" value="4"/>
    <input class="marker" type="text" value="5"/>
  </div>

</div>

Targetting the same by:

.input_range {
  .range {

  }
  .marker {

  }

  .subset .marker{
    &:nth-of-type(1) {
      background: black;
    }
  }
}

Or else you can always resort to javascript:

document.getElementsByClassName(‘marker’)[1].style.background = ‘black’;
Jibin Joseph
  • 1,265
  • 7
  • 13
  • Thank you. I was under the misunderstanding it could be used for both types and classes. I'll come up with a different solution, but this let me know where I went wrong. – Nicole Staline Apr 19 '19 at 17:47
  • @NicoleStaline if you took the time to read the duplicate question you will understand this without the need of reposting your question claiming that we aren't reading it. QUOTE from the duplicate: `The :nth-child() pseudo-class counts elements among all of their siblings under the same parent. It does not count only the siblings that match the rest of the selector. Similarly, the :nth-of-type() pseudo-class counts siblings sharing the same element type` – Temani Afif Apr 19 '19 at 19:39