Brooku Brooku - 2 months ago 8
jQuery Question

jQuery rearrange <li> in <ol>?

I'm trying to rearrange my list when a button is clicked, where the first one moves last, second moves fourth, third stays third and fifth moves first, it doesn't seem to take any effect, even the console is not showing anything.



$(document).ready(function() {
$("#rearranage").click(function() {

$.fn.orderChildren = function(order) {
this.each(function() {
var el = $(this);
for (var i = order.length; i >= 0; i--) {
el.prepend(el.children(order[i]));
}
});
return this;
};



$(".lists").orderChildren([
"#fifth",
"#fourth",
"#third",
"#second",
"first"
]);

});

});

<div class="hyperlinks">
<ol class="lists">
<li><a id="first" href="http://www.google.com">this</a></li>
<li><a id="second" href="http://www.google.com">is</a></li>
<li><a id="third" href="http://www.google.com">a</a></li>
<li><a id="fourth" href="http://www.google.com">test</a></li>
<li><a id="fifth" href="http://www.google.com">!</a></li>
</div>
</ol>
<button class="button" id="rearrange">rearrange this!</button>




mjw mjw
Answer Source

I made a fiddle for you: https://jsfiddle.net/6qoq3zrv/

HTML:

<div class="hyperlinks">
  <ol class="lists">
    <li class="block-item"><a id="first" href="http://www.google.com">this</a></li>
    <li class="block-item"><a id="second" href="http://www.google.com">is</a></li>
    <li class="block-item"><a id="third" href="http://www.google.com">a</a></li>
    <li class="block-item"><a id="fourth" href="http://www.google.com">test</a></li>
    <li class="block-item"><a id="fifth" href="http://www.google.com">!</a></li>
  </ol>
</div>
<input type="submit" id="rearrange">

JS:

$(document).ready(function(){
 $("#rearrange").click(function(){  
   $($(".block-item").get().reverse()).each(function() {
     $(this).appendTo($(this).parent());
   });
  });
});

Your hyperlinks will now be reversed when the rearrange button is clicked.