Reputation: 600
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?
Upvotes: 2
Views: 111
Reputation: 92461
document.getElementsByClassName()
is a live collection which means as you loop through the elements and change the class you are changing the collection. It's almost always a bad idea to alter the membership of a collection while you iterate over it. This makes your indexes point to the wrong elements. The easiest solution is to use querySelectorAll()
instead.
function change() {
var x = document.querySelectorAll('.a');
for (var y = 0; y < x.length; 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>
Upvotes: 3