jQuery reversing the order of child elements
JqueryJquery 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