className only changing every other class

后端 未结 15 2232
陌清茗
陌清茗 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-01 23:50

    Instead of using getElementsByClassName(),
    which returns a live HTMLCollection that will change as the classNames change,
    you can use querySelectorAll(),
    which returns a non-live NodeList that will not change.

    querySelectorAll() has better IE support than getElementsByClassName() (IE8+ vs. IE9+).
    It's also much more flexible since it supports CSS selectors (CSS2 for IE8+ and CSS3 for IE9+).

    However, querySelectorAll() is slower than getElementsByClassName().
    Keep that in mind if you're processing thousands of DOM elements.

    Snippet

    var blockSet = document.querySelectorAll(".block-default");
    var blockSetLength = blockSet.length;
    
    blockSet[0].className = "block-selected";
    blockSet[1].className = "block-selected";
    blockSet[2].className = "block-selected";
    blockSet[3].className = "block-selected";
    blockSet[4].className = "block-selected";
    blockSet[5].className = "block-selected";
    blockSet[6].className = "block-selected";
    blockSet[7].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

提交回复
热议问题