totoaussi
totoaussi

Reputation: 731

Javascript : can I re-order indexes of elements after an insertBefore or an appendChild method?

I have 3 div width class="childContainer" inside a parent container, like below :

<div id="parentContainer">

    <div class="childContainer"></div>
    <div class="childContainer"></div>
    <div class="childContainer"></div>

</div>

I can access these elements with :

parentContainer = document.getElementById("parentContainer");
childContainer = document.getElementsByClassName("childContainer");

Then, I move the first childContrainer to the last position by using :

parentContainer.appendChild(childContainer[0]);

So the element indexes of child containers become : 1, 2, 0 instead of 0, 1, 2.

But I want to re-order theses indexes so that element index 1 become 0, element index 2 become 1, and element index 0 become 2.

How can I do that ?

Upvotes: 0

Views: 302

Answers (2)

Brett DeWoody
Brett DeWoody

Reputation: 62851

When you create childContainers you're creating an HTMLCollection object. And:

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.

This means when you run parentContainer.appendChild(childContainer[0]); the HTMLCollection is updated, resulting in:

{
  "0": <div class="childContainer">1</div>,
  "1": <div class="childContainer">2</div>,
  "2": <div class="childContainer">0</div>,
  "length": 3,
  "item": function item() { [native code] },
  "namedItem": function namedItem() { [native code] }
}

which has reordered the elements so 0 is now 2, 1 is now 0, and 2 is now 1.

Here's an example - we'll append the first element to the end, then console.log the childContainers to see the indexes have changed.

parentContainer = document.getElementById("parentContainer");
childContainers = document.getElementsByClassName("childContainer");

parentContainer.appendChild(childContainers[0]);

console.log(childContainers)
<div id="parentContainer">

    <div class="childContainer">0</div>
    <div class="childContainer">1</div>
    <div class="childContainer">2</div>

</div>

Upvotes: 2

fethe
fethe

Reputation: 697

What if you use insertBefore() like this:

parentContainer.insertBefore(childContainer[0], childContainer[0]);

Upvotes: 0

Related Questions