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

前端 未结 4 862
灰色年华
灰色年华 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 14:50

    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;
    }
    Content Content
    Content Content
    Content Content

    提交回复
    热议问题