anascg
anascg

Reputation: 33

How to move a list item to a specified index(position) in an unordered list using Javascript

Lets say I've a following unordered list, How can I move "Three" to any index(position) in the list? The approach should be dynamic. Replacing the text content of an element is not an option. Because each list item will be containing other elements as well.

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  .
  .
  .
  <li>Hundred</li>  /* Nth List Element */
</ul>

Tried solutions from already answered similar questions. But didn't get the desired result.

I've already tried this

  1. Fetching the list in an Array through jQuery
  2. Used array.each to traverse the array
  3. Then used prepend to move the particular li to the top of the list

But through this approach I can only move the li element to the top of list. Not at any desired position.

Upvotes: 3

Views: 2716

Answers (4)

StackSlave
StackSlave

Reputation: 10627

I would use a constructor with an index based method for this:

function LiMover(liParent){
  this.kids = liParent.children;
  this.move = (index, beforeIndex = null)=>{
    const k = this.kids, e = k[index];
    if(beforeIndex === null){
      liParent.appendChild(e)
    }
    else{
      liParent.insertBefore(e, k[beforeIndex]);
    }
    return this;
  }
}
const liMover = new LiMover(document.querySelector('ul'));
liMover.move(0); // move 0 index (one) after last index
liMover.move(5, 0); // move 5 index (one) back to 0 index
liMover.move(1, 4); // move 1 index (two) to 4 index
liMover.move(3, 5).move(2, 0); // showing return this chain
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>  
</ul>

Upvotes: 2

pierrecode
pierrecode

Reputation: 222

try this swapping

  const listElts = Array.from(document.querySelectorAll('li'));
  const swap1 = listElts[2].textContent;
  const swap2 = listElts[4].textContent;
  listElts[2].textContent = swap2;
  listElts[4].textContent = swap1;

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76464

It's of course solvable. I have implemented a function which swaps two items of a collection:

function swap(items, first, second) {
    var aux = items[first].innerHTML;
    items[first].innerHTML = items[second].innerHTML;
    items[second].innerHTML = aux;
}

swap(document.querySelectorAll("ul > li"), 2, 4);

See the fiddle here: https://jsfiddle.net/5qropsvu/

Upvotes: 0

sol
sol

Reputation: 22939

const ul = document.querySelector('ul');
const items = [...ul.querySelectorAll('li')];

const moveItem = (from, to) => {
  if (to > items.length - 1 || to < 0) return;
  
  const item = items[from];
  if (!item) return;
  
  ul.removeChild(item);
  ul.insertBefore(item, ul.children[to]);
}

moveItem(5, 0);
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>  
</ul>

Upvotes: 2

Related Questions