Issue
.getElementsByClassName() is causing the issue. See below.
var a = document.getElementsByClassName("cc");
for (var i = 0; i < a.length; i++) {
console.log(`----- Loop ${i} -----`);
// Current HTML collection
console.log(a);
// Target element
console.log(`Target: ${a[i].textContent}`);
a[i].className = "cd";
}
<ul>
<li class="cc">A</li>
<li class="cc">B</li>
<li class="cc">C</li>
<li class="cd">D</li>
</ul>
How your for loop works:
a = [A, B ,C]
a[0] = A -> A.className = 'cd'
a = [B, C]
a[1] = C -> C.className = 'cd'
a = [B]
a[2] = undefined -> loop ends
Solution
Use .querySelectorAll() instead of .getElementsByClassName().
The former yields a static collection and the latter is dynamic (meaning that as you update the DOM, the collection itself is updated as well).
var a = document.querySelectorAll(".cc");
for (var i = 0; i < a.length; i++) {
a[i].className = "cd";
}
.cc {
background-color: blue;
}
.cd {
background-color: chartreuse;
}
<ul>
<li class="cc">A</li>
<li class="cc">B</li>
<li class="cc">C</li>
<li class="cd">D</li>
</ul>
Modern solution
Use .forEach() instead of for loop.
const a = document.querySelectorAll('.cc');
a.forEach(element => element.className = 'cd');
.cc {
background-color: blue;
}
.cd {
background-color: chartreuse;
}
<ul>
<li class="cc">A</li>
<li class="cc">B</li>
<li class="cc">C</li>
<li class="cd">D</li>
</ul>