className only changing every other class

后端 未结 15 2260
陌清茗
陌清茗 2020-12-01 23:41

I\'m performing a small text with JavaScript with the getElementsByClassName() and I am getting some unwanted results. I would like the script to change each CS

15条回答
  •  孤街浪徒
    2020-12-02 00:10

    function change() {
      var blockSet = document.getElementsByClassName("block-default");
      var blockSetLength = blockSet.length;
    
      for (var i = 0; i < blockSetLength; i++) {
    
        blockSet[0].className = "block-selected";
      }
    }
    .block-default {
      width: 100px;
      height: 50px;
      background-color: green;
      border: 1px solid red;
      padding: 10px;
    }
    .block-selected {
      width: 100px;
      height: 50px;
      background-color: blue;
      border: 1px solid white;
      padding: 10px;
    }
    
    
    
    BLOCK1
    BLOCK2
    BLOCK3
    BLOCK4
    BLOCK5
    BLOCK6
    BLOCK7
    BLOCK8

    what you were doing wrong is every time you change the class the colllection re-evaluates and decreases in size.

提交回复
热议问题