How to change class for all elements retrieved by document.getElementsByClassName

前端 未结 4 856
灰色年华
灰色年华 2020-12-10 14:18

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

4条回答
  •  借酒劲吻你
    2020-12-10 15:15

    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

提交回复
热议问题