1

So I have a list of children from a DOM element. I take the child list and push it to an empty array. When I appendChild the array elements one by one, why does it change the position of the children elements? Shouldn't it effect only the array?

var listItemsContainer = document.getElementById("$content_id");
var items = listItemsContainer.children;
var itemsArr = [];
var continentcontainer = document.getElementById('continents');

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

itemsArr.sort(function(a, b) { //sorting itemsArr (array of listItems) A to Z
  return a.innerHTML == b.innerHTML ?
    0 :
    (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (var i = 0; i < itemsArr.length; ++i) {
  continentcontainer.appendChild(itemsArr[i]); //append child moves item from current location into new location
}
Piyin
  • 1,823
  • 1
  • 16
  • 23
Ryan Smith
  • 98
  • 1
  • 9

2 Answers2

1

Your array cannot hold DOM Elements, only their respective pointers.

The order of these pointers in your array has no significance to DOM. It's like keeping a list of people in the room. Some may change their positions and others may even leave - but your list will stay as is, and counting people that are no longer in the room and will no longer reflect their order in your list.

You are trying to sort (reorder) your DOM elements by pushing their references in an array - that's not possible.

This answer has been answered here: Why doesn't htmlCollection inherit from array

And here is the way to sort DOM Elements using Array: JavaScript sorting issue with looping

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
0

change

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

to

for (var i = 0; i < items.length; i++) {
  itemsArr.push(items[i].cloneNode(true));
} 

for...in should not be used to iterate over an Array where the index order is important. MDN

themefield
  • 3,847
  • 30
  • 32
  • Thanks! This puts me on the right track, I just have to prevent the if statement containing this section from creating several clones of the huge list of items I have. – Ryan Smith Nov 17 '17 at 21:55
  • @RyanSmith I guess when those children moved to a new parent, and rendered in a different order after sorting, that might be very confusing. – themefield Nov 17 '17 at 22:10
  • Yeah, I noticed that only the elements that were there before they were cloned were sorted. – Ryan Smith Nov 17 '17 at 22:21