-3

I'm an absolute JS beginner. I would appreciate your help for the following: I have the following HTML code. How can I change the order of li-s in a list when I press a button with JS? i.e.: Item1 should become Item2 and so on. I think it's possible to do this with "for(){}", I just don't know exactly how..

<ul>
    <li>Item 1</li> 
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>
<button>Click Me</button>
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 4
    Have a try, come back when and if you get stuck on something – Liam Jan 20 '17 at 11:24
  • You don't specify the logic of order changing. Item 1 will become Item 2, when I press the button again, what will happen next and why? If you're absolute beginner, look at this: https://jqueryui.com/sortable/ – meehocz Jan 20 '17 at 11:28
  • Possible duplicate of [jQuery reversing the order of child elements](http://stackoverflow.com/questions/5347839/jquery-reversing-the-order-of-child-elements) – Meer Jan 20 '17 at 11:34

3 Answers3

1

We need to start with picking the list we're actually planning to modify:

var listToModify = document.querySelector("ul");

Next, we need to get an iterator through the list items to shuffle around:

var listItemsToShuffle = listToModify.querySelectorAll("li");

Then we want to loop through our items and move them. I'm going to assume that reordering the list results will result in "Item4" ending up on the top.

for (var i = 0; i < listItemsToShuffle.length - 1; i++) {
    listToModify.appendChild(listItemsToShuffle[i]);
}

It seems like we're duplicating the list items but we're not. Same element/node cannot be duplicated (exist in two places), so the first one will be removed.

Philip P.
  • 1,162
  • 1
  • 6
  • 15
0

Hopefully this would help you

var __ListItem = document.getElementById("listItemId");
function __shuffleList() {
    var __nodes = __ListItem .children, i = 0;
    __nodes = Array.prototype.sort.call(__nodes );
    while(i < __nodes .length) {
       __ListItem .appendChild(__nodes [i]);
       ++i;
    }
}
__shuffleList();
AKHIL
  • 135
  • 3
-1

Try this

$('#btnrev').click(function(){

$('ul').html($('ul').find('li').get().reverse());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

<button id="btnrev">
click
</button>
Meer
  • 2,765
  • 2
  • 19
  • 28