javascript – Why does appendChild change based on order of elements?-ThrowExceptions

Exception or error:

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

I want to move to elements from one div to another using JavaScript. When I loop through and the divs they are moving TO is first it works. But when the div they are moving FROM is first it doesn’t work. Why?

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("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 = "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>
How to solve:

getElementsByClassName returns a live node list.

In the first example, when you move New Audio it is still the 0th item in the collection because you moved it to earlier in the document.

In the second example, when you move New Audio to later in the document it becomes the 1st element in the collection (you are changing the order of the elements that are members of that class) so when you increment i to 1 you append New Audio again and you never append New Folder (because you skipped over it when it was moved to position 0).

You probably want to use Array.from to convert the live node list into a static array.

Leave a Reply

Your email address will not be published. Required fields are marked *