if the LI tag has a class of active it will go to the last position

Tags: , ,



I have multiple li tag, if the user clicks one of those tags it will have a class of active and then the li tag will go to the end position of the list. but if the user decided to click the li tag it will remove the class and the li tag will go back to the previous position.

$(document).ready(function(){
$("button.move").on('click', function(){
  $(".active").insertAfter("li:last-child()");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="move">move</button>
    <ul>
    <li class="active">1st list item</li>
    <li>2nd list item</li>
    <li>3rd list item</li>
    </ul>

Answer

You could make your list flex (or grid as david mentions in the comments) and use the order property on the li when you want to re-order them.

So no real change is happening in the DOM, but the .active element will be shown in the end.

document.querySelector('ul').addEventListener('click', (e) => {
  const element = e.target;
  const isLI = element.nodeName === 'LI';
  if (isLI) {
    element.classList.toggle('active');
    removeClassFromSiblings(element, 'active');
  }
})

function removeClassFromSiblings(element, classname) {
  let prev = element;
  let next = element;
  // remove active from preceeding elements
  while (prev = prev.previousElementSibling) {
    prev.classList.remove('active');
  }
  // remove active from following elements
  while (next = next.nextElementSibling) {
    next.classList.remove('active');
  }
}
ul {
  display: flex; /* or grid */
  flex-direction: column; /* if using flex */
}

.active {
  order: 1;
  color: red;
}
<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <li>fifth</li>
  <ul>


Source: stackoverflow