Home > OS >  JavaScript toggler works only once
JavaScript toggler works only once

Time:09-30

I have a button which has to toggle classes between 4 divs. The HTML, CSS and JS files are below, I'm looking for creating a single toggler button not two.

function toggleColor() {
  var box = document.getElementsByClassName("wrapper");
  for (var x = 0; x < box.length; x  ) {
    box[x].innerHTML = box[x].innerHTML.replace(/class="(red|green)"/gi,
      g1 => {
        return (g1 == "red") ? "class=\"red\"" : "class=\"green\""
      });
  }
}
.wrapper * {
  width: 100px;
  height: 100px;
  margin: 100px;
}

.red {
  background: #f00;
}

.green {
  background: #0f0;
}
<button onclick="toggleColor()">toggle</button>

<div class="wrapper">
  <div class="red"></div>
  <div class="red"></div>
  <div class="red"></div>
  <div class="red"></div>
</div>

CodePudding user response:

You can use querySelectorAll to get a nodeList that matches the selector.

With each node in the list you can use classList.toggle to swap the class.

function toggleColor() {
  const boxes = document.querySelectorAll('.box')
  boxes.forEach(box => {
    box.classList.toggle('red')
    box.classList.toggle('green')
  })
}
.wrapper * {
  width: 100px;
  height: 100px;
  margin: 100px;
}

.red {
  background: #f00;
}

.green {
  background: #0f0;
}
<button onclick="toggleColor()">toggle</button>

<div class="wrapper">
  <div class="box red"></div>
  <div class="box red"></div>
  <div class="box red"></div>
  <div class="box red"></div>
</div>

CodePudding user response:

You can use classList.toggle to add and remove a class from an element. Adding an additional class to an existing one will override its CSS properties.

function toggleColor() {

  let boxes = document.querySelectorAll('.red');

  boxes.forEach(box => {
    box.classList.toggle('green');
  });


}
.wrapper * {
  width: 100px;
  height: 100px;
  margin: 100px;
}

.red {
  background: #f00;
}

.green {
  background: #0f0;
}
<button onclick="toggleColor()">toggle</button>

<div class="wrapper">
  <div class="red"></div>
  <div class="red"></div>
  <div class="red"></div>
  <div class="red"></div>
</div>

CodePudding user response:

.wrapper * {
  width: 100px;
  height: 100px;
  margin: 100px;
}

.red {
  background: #f00;
}

.green {
  background: #0f0;
}
<html>

<body>
  <button onclick="toggleColor()">toggle</button>

  <div class="wrapper">
    <div class="red"></div>
    <div class="red"></div>
    <div class="red"></div>
    <div class="red"></div>
  </div>
  <script>
    function toggleColor() {
      const elements = document.querySelectorAll('.wrapper > div');
      elements.forEach((element) => {
        if (element.className === 'red') {
          element.className = 'green'
        } else if (element.className === 'green') {
          element.className = 'red'
        }
      })
    }
  </script>
</body>

</html>

  • Related