Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
How to increment a class number to switch divs?

I would like to switch my divs (I'm creating a div carousel style) with their class name. So I would like to increment and decrement (to go 'next' and 'previous') the "box'1'" number to switch between them anytime I click on the buttons, which contain the js functions

<div class="box1"> ...
</div>
<div class="box2"> ...
</div>
<div class="box3"> ...
</div>
<div class="box4"> ...
</div>

I found some fixes on this site but still I wasn't able to use them for my code. So I tried this :

function increase() {
  var a = 1;
  var boxes = document.getElementById("box1");
  boxes.value = a;
  a++;
}

function decrease() {
  var a = 1;
  var boxes = document.getElementById("box1");
  boxes.value = a;
  a--;
}

And

<input class="buttongray" value="next" onclick="increase()">
<input class="buttonblue" value="back" onclick="decrease()">
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

let box = document.querySelectorAll('.box');
let ctr = 0;
// onload fill box 1
box[ctr].style.display = "block";
box[ctr].innerHTML = "Box On " + (ctr+1);

function ctrSwitch(n) {
  // int counter
  ctr += n;

  // counter check max and min
  ctr = (ctr>=box.length)? 0 : (ctr < 0) ? box.length-1: ctr;

  // loop and match active box by counter
  box.forEach((el, i) => {
    /* @param el = box[i] */
    // option 1 (use ternary);
    // box[i].innerHTML = (ctr == i)? `Box On ${ctr+1}` : "...";

    // option 2 (use if else);
    if ( ctr == i ) {
       el.style.display = "block";
       el.innerHTML = `Box On ${ctr+1}`;
    }
    else {
       el.style.display = "none";
       el.innerHTML = `...`;
    }
  });
}
.box {
  width: 50px;
  height: 50px;
  display: none;
  color: #fff;
}

.box1 {
  background: red;
}
.box2 {
  background: green;
}
.box3 {
  background: blue;
}
.box4 {
  background: purple;
}
<div class="box box1"> ...
</div>
<div class="box box2"> ...
</div>
<div class="box box3"> ...
</div>
<div class="box box4"> ...
</div>
<button onclick="ctrSwitch(-1)">Prev</button>
<button onclick="ctrSwitch(1)">Next</button>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!