Imagine having 3 unique classes: alpha, beta, and gamma. Each class contains 3 individual div elements like so:
<div class="alpha"></div>
<div class="alpha"></div>
<div class="alpha"></div>
<div class="beta"></div>
<div class="beta"></div>
<div class="beta"></div>
<div class="gamma"></div>
<div class="gamma"></div>
<div class="gamma"></div>
Now, assign variables to each class:
var a = document.getElementsByClassName("alpha");
var b = document.getElementsByClassName("beta");
var c = document.getElementsByClassName("gamma");
Combine them all into an array named elements:
var elements = [a, b, c];
If the goal is to change the text color of all div elements within the classes alpha, beta, and gamma, how can this be achieved without multiple loops like below:
function changeColor() {
var j;
for (j = 0; j < a.length; j++) {
a[j].style.color = "blue";
}
for (j = 0; j < b.length; j++) {
b[j].style.color = "blue";
}
for (j = 0; j < c.length; j++) {
c[j].style.color = "blue";
}
}
It would be great to use only one loop to go through the elements array and change the text color of all divs within each class dynamically.