className only changing every other class

后端 未结 15 2175
陌清茗
陌清茗 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

    Because you change the .className of the blockSet which is an HTMLCollection. The collection that have elements with same class (block-default) will change when the elements suffers some updates.

    In other words when you change the .className of an element the collection will exclude that element. This means that the size of the HTMLCollection will decrease . Also the size will increase if an element with that class has beed added to the DOM.

    To solve this you can always change only the first element .className.

    for(var i = 0; i

    Notes: Intead of changing class element by element, you can iterate through elements with for and change .className.

    var blockSet = document.getElementsByClassName("block-default");
    var blockSetLength = blockSet.length;
    
    console.log(blockSet);
    
    for(var i = 0; i
    .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

    If you add a new item in DOM (not collection) the size will increase as presented in the example below.

    var blockSet = document.getElementsByClassName("block-default");
    var blockSetLength = blockSet.length;
    
    alert("Current size: " + blockSet.length);
    document.body.innerHTML += '
    BLOCK9
    '; alert("After adding an element in DOM size: " + blockSet.length);
    .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

提交回复
热议问题