I have a table which contains 3 rows. Each row has the class: .myClass
.
I then query for the table rows with document.getElementsByClassName(\'myC
As georg pointed out in his answer, getElementsByClassName returns a "live" collection. That means the array will "update" as the elements change.
To fix your problem, you should use a while loop, iterating while x.length
exists, and only changing the first element of the HTMLCollection
.
var c = document.getElementsByClassName('myTable')[0];
var x = c.getElementsByClassName('myClass');
while (x && x.length) {
x[0].className = 'otherClass'
}
var y = c.getElementsByClassName('otherClass');
alert(y.length);
.myClass {
display:block;
background-color: red;
}
.otherClass {
display:block;
background-color:green;
}
<table class="myTable">
<tr class="myClass2">
<td>Content</td>
<td>Content</td>
</tr>
<tr class="myClass">
<td>Content</td>
<td>Content</td>
</tr>
<tr class="myClass">
<td>Content</td>
<td>Content</td>
</tr>
<table>
getElementsByClassName
, like other HTML collections, is "live", that is, when you assign another class name to its member, it's removed from the collection on the fly and its length gets decremented. That's why your loop runs only once.
var x = document.getElementsByClassName('myClass');
alert("before: " + x.length);
x[0].className='otherClass';
alert("after: " + x.length);
.myClass { color: black }
.otherClass { color: red }
<b class="myClass">hi</b>
<b class="myClass">hi</b>
Docs:
An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.
To answer in context to your question, you could set the className of the first element until there are none left in the collection:
while(x.length > 0) {
x[0].className = 'otherClass';
}
Another option is populating a normal array with the elements and then iterate through this array. You will be able to chance the class names of the elements this way.
Georg is right. Elements array is updated on the fly, so you cannot depend on it's length;
Try this code:
var c = document.getElementsByClassName('myTable')[0],
x = c.getElementsByClassName('myClass');
while (x.length) {
x[0].className = 'otherClass';
}
var y = c.getElementsByClassName('otherClass');
alert(y.length);
Working fiddle