I tried the following code :
var a = document.getElementsByClassName("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>
This only updates the alternate list items and not all of them having the same class. I would like to know the reason why this isn't working.
.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 endsUse .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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With