How to increase the class name number(item1,item2,item3) on clicking a button

Hi… I have made a div’s with classes like slide1, slide2, slide3 and so on.
i want to add some js function to them. but one by one. on clicking a button on my page.

FOR EXAMPLE

I Have five div’s of same color, now i want them to be of different colors on clicking a button.
suppose all div’s are red. Now when i click a button i want the 2nd div to be blue and all other stay red. and again when i click the button, The 3rd div will be blue and all other stay red. and so on.

//

So i want to increase the number in slide’1’,slide’2’ and so on using js.
I had tried using for loops making i++ things but is did’t work
and some other things but they didn’t work as expected. so can anyone help me.

HERE IS THE CODE

<body>
  <div class="quiz-field">
    <div class="slides slide1">
    </div>
    <div class="slides slide2">
    </div>
    <div class="slides slide3">
    </div>
    <div class="slides slide4">
    </div>
    <div class="slides slide5">
    </div>  
  </div>
  <button onclick="myfun()">Click me</button>
</body>

did you solve it yet ? Or are you still figuring out ?

i tried so many things …i am still figuring it out…can you help me.

1 Like

Sure i will inbox you wait.

Sorry i was lil busy .Anyway i coded a quick codepen regarding what you want to achieve.
Take a look :rocket: https://codepen.io/RocktimSaikia/pen/xxxpbbz

Let me know if you need any help

2 Likes

Just use :nth-child pseudo-selector rather than classes to select an html elements.

Thanks…for taking out the time and helping me.
can you please explain the logic behing the code?

Sure. Here how it goes :

  1. first i get all the box elements and then i change
    the color of the each box element when the button is clicked.

  2. I keep a counter so that every time the function is executed ,the counter gets incremented by 1, meaning the next change is gonna be applied to the next button and so on.

  3. As you also want to keep the other boxes the same color except the targeted one so
    i made all the box color red at the start of the function.

  4. And when the counter and box elements length are same , I set the counter to 0 so
    that it starts all over again.

@RocktimSaikia
thank you very much…:grinning::grinning:

1 Like

Sure if you get stuck again you can inbox me directly. I’ll try to help whenever i’m available. :+1:

1 Like