代码之家  ›  专栏  ›  技术社区  ›  Marvin

为什么appendChild会根据元素的顺序进行更改?

  •  0
  • Marvin  · 技术社区  · 6 年前

    https://jsfiddle.net/L835jsym/6/

    const newButtonEls = document.getElementsByClassName("new-button");
    for (let i = 0; i < newButtonEls.length; i++) {
      const container = document.getElementsByClassName('new-media-btn-container')[0];
      container.appendChild(newButtonEls[i]);
    }
    <div class = "new-media-btn-container">
      <p>Should be inserted below</p>
    </div>
    <div class = "two">
      <p>Should not be inserted below here anymore</p>
      <button class = "new-button">New Audio</button>
      <button class = "new-button">New Folder</button>
    </div>

    const newButtonEls=document.getElementsByClassName(“新建按钮”);
    const container=document.getElementsByClassName('new-media-btn-container')[0];
    container.appendChild(newButtonEls[i]);
    <div class = "two">
      <p>Should not be inserted below here anymore</p>
      <button class = "new-button">New Audio</button>
      <button class = "new-button">New Folder</button>
    </div>
    <div class = "new-media-btn-container">
      <p>Should be inserted below</p>
    </div>
    1 回复  |  直到 6 年前
        1
  •  1
  •   Quentin    6 年前

    getElementsByClassName 返回 节点列表。

    在第一个例子中,当你移动 New Audio 它是 仍然 这个 0 集合中的项,因为您已将其移到文档的早期位置。

    在第二个例子中,当你移动 后来 1 集合中的st元素(您正在更改属于该类的元素的顺序),因此当您增加 i 1个 新音频 再一次 New Folder (因为当它移动到位置时,您跳过了它) 0个 ).

    你可能想用 Array.from 将活动节点列表转换为静态数组。