-2

`

<div class="main">
  <div class="box" data-index="1"></div>
  <div class="box" data-index="2"></div>
  <div class="box" data-index="3"></div>
  <div class="box" data-index="4"></div>
  <div class="box" data-index="5"></div>
  <div class="box" data-index="6"></div>
  <div class="box" data-index="7"></div>
  <div class="box" data-index="8"></div>  
</div>

`

i want to select every 4n child by data-index attribute (not by nth child property). want data-index=4 & data-index=8 should be color blue. how to deal with this.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • 1
    Not possible with CSS – Paulie_D Oct 29 '22 at 15:39
  • write manually all the cases if you know that your data is limited. You will probably need 5 or 6 selector at most – Temani Afif Oct 29 '22 at 15:47
  • Attribute values are strings. You can't create any "numerical" logic with it: https://stackoverflow.com/questions/31614630/is-it-possible-to-select-all-elements-with-an-attribute-value-greater-than-a-cer `div[data-index]:nth-child(4n)` would work, but it will ignore the actual value inside the attribute. – ChenBr Oct 29 '22 at 16:58

1 Answers1

0

As far as I understood, you can't do this with CSS, you have to use Javascript for this one:

// If you want to start from the first element then use 0 or otherwise use 4 as the starting point
for (let i = 4; i < document.querySelectorAll('.box').length; i += 4) {
    document.querySelector(`[data-index=${i}]`).style.color = "blue";
}
Dev-Siri
  • 592
  • 5
  • 22
  • Hey dev this is great solution but can you help me achieve this thing using Swiper JS (React) ? Slide 1 Slide 2 Slide 3 Slide 4 I want to add a bg color in every 2th index in this slider – sourav roy Oct 29 '22 at 16:04
  • Sorry but I am not sure how to use it with SwiperJS (I don't use it) – Dev-Siri Oct 29 '22 at 16:13