jQuery reversing the order of child elements

Jquery

Jquery Problem Overview


What is the best way to reverse the order of child elements with jQuery.

For example, if I start with:

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

I want to end up with this:

<ul>
  <li>C</li>
  <li>B</li>
  <li>A</li>
</ul>

Jquery Solutions


Solution 1 - Jquery

var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());

Solution 2 - Jquery

Edit: Anurag's answer is better than mine.

ul = $('#my-ul'); // your parent ul element
ul.children().each(function(i,li){ul.prepend(li)})

If you call .prepend() on an object containing more than one element, the element being appended will be cloned for the additional target elements after the first, so be sure you're only selecting a single element.

Solution 3 - Jquery

Try this:

$(function() {
  $.fn.reverse = [].reverse;
  var x = $('li');
  $('ul').empty().append(x.reverse());
});

Solution 4 - Jquery

All the answer given before me are best but you can try this also

$('#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>

Solution 5 - Jquery

oneliner:

$('ul').append($('ul>').detach().get().reverse());

Solution 6 - Jquery

No Jquery Solution

Element.prototype.reverse = function(){
    var c = [].slice.call(this.children).reverse();
    while (this.firstChild) { this.removeChild(this.firstChild); };
    c.forEach(function( child ){ this.appendChild(child) }.bind(this))
}

And use like :

document.querySelector('ul').reverse(); // children are now reversed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontilleryjView Question on Stackoverflow
Solution 1 - JqueryAnuragView Answer on Stackoverflow
Solution 2 - JqueryundefinedView Answer on Stackoverflow
Solution 3 - Jqueryuser342706View Answer on Stackoverflow
Solution 4 - JqueryMeerView Answer on Stackoverflow
Solution 5 - JqueryDieter BenderView Answer on Stackoverflow
Solution 6 - Jqueryuser4602228View Answer on Stackoverflow