2

Today I have a question: How to change index of elements via plain JS? I have this example code:

<div class="foo">
    <div class="f6x1"></div>
    <div class="f6x2"></div>
    <div class="f6x3"></div>
</div>

So I want to change order of (for example) first element, like this:

<div class="foo">
    <div class="f6x2"></div>
    <div class="f6x1"></div>
    <div class="f6x3"></div>
</div>

Is there any "non-laging" example how to do that?

PDKnight
  • 712
  • 6
  • 25

2 Answers2

2

You need to select element and the move it before the next element after the second:

var first = document.querySelector('.f6x1'),
    next  = first.nextElementSibling;

first.parentNode.insertBefore(first, next.nextElementSibling);
<div class="foo">
    <div class="f6x1">1</div>
    <div class="f6x2">2</div>
    <div class="f6x3">3</div>
</div>

Reference:

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

A more generic way to order the elements in any order you need:

first, start indexing using data-*-attributes:

<div class="foo">
    <div data-index="1" class="f6x1"></div>
    <div data-index="2" class="f6x2"></div>
    <div data-index="3" class="f6x3"></div>
</div>

Second, use a function to reorder, something like:

var sortElement = document.querySelector('[data-sortable]');

document.querySelector('#buttonblock').addEventListener('click', doSort);

function doSort(e) {
  var origin = e.target || e.srcElement;
  if (/button/i.test(origin.nodeName)) {
    var sortorder = origin.getAttribute('data-order').split(',');
    orderElements(sortElement, sortorder);
  }
  return true;
}

function orderElements(elementRoot, order) {
  var placeholder = document.createElement('div');
  while(order.length) {
    var current = order.shift();
    var element = elementRoot.querySelector('[data-index="'+current+'"]');
    if (element) {
     placeholder.appendChild(element);
    }
  }
  elementRoot.innerHTML = '';
  elementRoot.innerHTML = placeholder.innerHTML;
}
<div data-sortable="true" class="foo">
  <div data-index="1" class="f6x1">f6x1</div>
  <div data-index="2" class="f6x2">f6x2</div>
  <div data-index="3" class="f6x3">f6x3</div>
</div>

<div id="buttonblock">
  <button data-order="2,1,3">sort 2, 1, 3</button>
  <button data-order="3,2,1">sort 3, 2, 1</button>
  <button data-order="3,1,2">sort 3, 1, 2</button>
</div>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • @Kooilnc I think it's very large code (see dfsq's answer), but it shows another way how to do it :) By the way, I don't want to touch the code. – PDKnight Feb 22 '15 at 18:59