Issue
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>
Solution
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>
Answered By - ksav
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.