I am new to javascript and am learning arrays and loops. I was writing some basic code to change classes of some paragraphs, but am unable to do so. Can anyone tell me what am I doing wrong in it?
function change() {
var x = document.getElementsByClassName('a');
x[0].className = 'b';
for (var y = 0; y < x.length; y++) {
console.log(x[y]);
x[y].className = "b";
}
}
p.a {
font-size: 2em;
color: red;
text-align: center;
}
p.b {
font-size: 1em;
color: green;
text-align: center;
}
<p class='a'>a</p>
<p class='a'> b</p>
<p class='a'>c</p>
<p class='a'>a</p>
<p class='a'>b</p>
<p class='a'>c</p>
<p class='a'>a</p>
<p class='a'>b</p>
<p class='a'>c</p>
<button onclick="change()">Change</button>
As it turns out some paragraphs are changing and some are not can anyone tell what am I doing wrong?
getElementsByClassName()returns a live node collection. Since as you change the classes, those elements are removed from the collection.